如何声明在Kotlin随播对象中声明的本机cpp方法? [英] How to declare native cpp method for which declared in kotlin companion object?
问题描述
我有一个Kotlin类,它只声明了一些Kotlin和C/C ++交互的方法:
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
}
推荐答案
伴随对象被实现为内部类JNILib$Companion
的实例.该$
必须出现在C ++函数的签名中,并且
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).
这篇关于如何声明在Kotlin随播对象中声明的本机cpp方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!