Kotlin, NDK and C++ interactions

前端 未结 1 807
遇见更好的自我
遇见更好的自我 2020-12-11 11:45

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

相关标签:
1条回答
  • 2020-12-11 12:29

    Ok, thanks to @Richard, here is my wrapper

    ObjectWrapper.kt

    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

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题