如何从 Kotlin 调用静态 JNI 函数?
How to call a static JNI function from Kotlin?
在 Java 中这不是问题,但在 Kotlin 中,我们没有静态。我们有用于相同目的的伴生对象,但是,作为额外的对象,它们在 JNI 调用中得到一个损坏的名称 (Java_package_Type00024Companion_function),这与 JNI 的期望不匹配。从主 class 调用它,显然会导致 GetStaticMethodID
.
中的 JNI 错误
解决方法是在 Java 中创建一个包装器并使用 Kotlin 中的包装器。
你在jni调用中可以参考的@JvmStatic
annotation can be added to the function defined on the companion object to cause the generation of a static method
来自链接的 kotlin 文档:
class C {
companion object {
@JvmStatic fun callStatic() {}
fun callNonStatic() {}
}
}
// java
C.callStatic(); // works fine
C.callNonStatic(); // error: not a static method
在 kotlin 中使用外部关键字。
external fun nativeKey1() : String?
keys.c class:
Java_com_mobile_application_MyApplication_00024Companion_nativeKey1(
JNIEnv *env, jobject thiz) {
static const char randomStr[] = "89!Q4q+x#f6~iOL9@&c>2JY!s!x@2Ai-SbHYA@EenokBTE#NoTiE6jl4-5zovso@2Ai-SbHYAEenokBNoTiE6jl4SbHYA@EenokBTE";
char key[17] = {0};
// Start garbage code
int i = 0;
float j = 0;
int loop_count = 0;
for (i=0; i < loop_count; i++) {
int n = (i / 2) + 29 + i + 17;
key[0] = randomStr[n];
}
在 Java 中这不是问题,但在 Kotlin 中,我们没有静态。我们有用于相同目的的伴生对象,但是,作为额外的对象,它们在 JNI 调用中得到一个损坏的名称 (Java_package_Type00024Companion_function),这与 JNI 的期望不匹配。从主 class 调用它,显然会导致 GetStaticMethodID
.
解决方法是在 Java 中创建一个包装器并使用 Kotlin 中的包装器。
你在jni调用中可以参考的@JvmStatic
annotation can be added to the function defined on the companion object to cause the generation of a static method
来自链接的 kotlin 文档:
class C { companion object { @JvmStatic fun callStatic() {} fun callNonStatic() {} } }
// java C.callStatic(); // works fine C.callNonStatic(); // error: not a static method
在 kotlin 中使用外部关键字。
external fun nativeKey1() : String?
keys.c class:
Java_com_mobile_application_MyApplication_00024Companion_nativeKey1(
JNIEnv *env, jobject thiz) {
static const char randomStr[] = "89!Q4q+x#f6~iOL9@&c>2JY!s!x@2Ai-SbHYA@EenokBTE#NoTiE6jl4-5zovso@2Ai-SbHYAEenokBNoTiE6jl4SbHYA@EenokBTE";
char key[17] = {0};
// Start garbage code
int i = 0;
float j = 0;
int loop_count = 0;
for (i=0; i < loop_count; i++) {
int n = (i / 2) + 29 + i + 17;
key[0] = randomStr[n];
}