问题
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