本文介绍了如何声明在Kotlin随播对象中声明的本机cpp方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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 ++函数的签名中,并且完成该操作的方法是使用转义序列_0XXXX,其中XXXX是Unicode字符代码. $的字符代码为十六进制24,即转义序列为_00024,这意味着您的C ++函数名称变为Java_com_package_JNILib_00024Companion_getAppId.

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.

或者,您可以通过 @JvmStatic . C ++函数名称应为Java_com_package_JNILib_getAppId,并带有参数JNIEnv *, jclass(请注意,由于getAppId现在是类方法而不是实例方法,因此请注意jclass而不是jobject).

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方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:49