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

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

问题描述

我不熟悉 Android NDK,我需要帮助来使用 C++ 编写的本机部分代码构建 Kotlin 应用程序.我找到了使用基本 C 函数的 HelloWorld 示例,但没有使用 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,但方法以完整的包名称命名.在这里,我不得不在 kotlin 世界和原生世界之间进行翻译.

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天全站免登陆