Kotlin,NDK和C ++交互 [英] Kotlin, NDK and C++ interactions

查看:477
本文介绍了Kotlin,NDK和C ++交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉Android NDK,我需要使用C ++编写的本机代码来构建Kotlin应用程序的帮助.我发现HelloWorld示例使用基本的C函数,但没有使用C ++对象的示例或教程.

I'm not familiar with the Android NDK and I need help to build a Kotlin application using native part of code written in C++. I've found HelloWorld sample using a basic C function but no examples or tutorial using C++ objects.

假设我有一个C ++对象,带有hpp和cpp文件:

Let's say I have a C++ object, with hpp and cpp file:

object.hpp

#ifdef object_hpp
#define object_hpp
//
// include part
//

class Object {
  // some stuff
}
#endif

object.cpp

#include "object.hpp"

Object::Object()
{
  //constructor
}

std::string Object::sayHello(std::string value)
{
  // do stuff
}

我想知道在Kotlin应用程序中使用它的最佳方法是什么

I want to know what is the best way to use it in a Kotlin app:

  • 我必须首先生成一个库(.so或.a吗?)并将其导入到我的应用程序中?如果是这样,C ++代码是否有任何更改?
  • 我可以将这些C ++文件导入到我的项目中吗(有了C ++支持,我知道)?如果是,该如何使用?

我已经读过有关JNIEXPORTJava_my_package_name_SomeClass_someMethod()的信息,但是我不确定如何使用它:我需要修改C ++代码本身还是应该为其开发包装器?

I've read about JNIEXPORT and Java_my_package_name_SomeClass_someMethod() but I'm not sure how to use it: do I need to modify the C++ code itself or should I develop a wrapper to it ?

在此先感谢您的帮助.

推荐答案

好,感谢@Richard,这是我的包装器

Ok, thanks to @Richard, here is my wrapper

ObjectWrapper.kt

公开我要使用的API.该方法的关键字external表示主体在其他位置.就我而言,是在包装的本机层中.

Exposes the API I want to use. The keyword external of the method indicates that the body is elsewhere. In my case, in the native layer of the wrapper.

class ObjectWrapper {

    companion object {
        init {
            System.loadLibrary("mylibrary")
        }
    }

    external fun sayHello(name: String): String
}

MyLibrary.cpp

与kotlin部分相同的API,但是方法使用完整的包名称来命名.在这里,我要谈谈科特林世界与本土世界之间的转换.

Same API as the kotlin part but the methods are named with the completed package name. Here, I have to the translation between the kotlin world and the native world.

#include <jni.h>
#include <string>
#include "Object.h"

static Object *pObject = NULL;

extern "C" {
    JNIEXPORT jstring Java_com_packagename_ObjectWrapper_sayHello(
            JNIEnv *env,
            jobject /* this */,
            jstring input) {
        pObject = new Object();
        const char *msg = env->GetStringUTFChars(input, JNI_FALSE);
        std::string hello = pObject->getHelloString(msg);
        return env->NewStringUTF(hello.c_str());
    }
}

这篇关于Kotlin,NDK和C ++交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆