How to declare native cpp method for which declared in kotlin companion object?

做~自己de王妃 提交于 2020-04-11 18:32:20

问题


I have a Kotlin class which just declare some methods for interaction of Kotlin and C/C++ :

class JNILib {

    companion object {

        external fun getAppId(): String

        init {
            System.loadLibrary("native-code")
        }
    }
}

But I have a problem when declaring the native method. I tried

extern "C"
JNIEXPORT jstring JNICALL
Java_com_package_JNILib_getAppId(
        JNIEnv *env, jobject /* this */){
    // wrong
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_package_JNILib_Companion_getAppId(
        JNIEnv *env, jobject /* this */){
    // wrong
}

回答1:


The companion object is realized as an instance of an inner class JNILib$Companion. That $ must be present in the C++ function's signature, and the way you accomplish that is by using the escape sequence _0XXXX, where XXXX is the unicode character code. The character code for $ is hex 24, i.e. the escape sequence is _00024, which means that your C++ function name becomes Java_com_package_JNILib_00024Companion_getAppId.

Alternatively, you could make getAppId a static method of JNILib by annotating it with @JvmStatic. Your C++ function name should then be Java_com_package_JNILib_getAppId, with the arguments JNIEnv *, jclass (note the jclass instead of jobject since getAppId now is a class method rather than an instance method).



来源:https://stackoverflow.com/questions/49554430/how-to-declare-native-cpp-method-for-which-declared-in-kotlin-companion-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!