如何声明在Kotlin随播对象中声明的本机cpp方法? [英] How to declare native cpp method for which declared in kotlin companion object?

查看:94
本文介绍了如何声明在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 ++函数的签名中,并且

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆