如何声明在kotlin伴侣对象中声明的本地cpp方法?

时间:2018-03-29 11:02:57

标签: android android-ndk kotlin kotlin-android-extensions

我有一个Kotlin类,它只是为Kotlin和C / C ++的交互声明了一些方法:

class JNILib {

    companion object {

        external fun getAppId(): String

        init {
            System.loadLibrary("native-code")
        }
    }
}

但是在声明本机方法时我遇到了问题。我试过了

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 个答案:

答案 0 :(得分:4)

伴侣对象被实现为内部类JNILib$Companion的实例。 $必须存在于C ++函数的签名中,the way you accomplish that是使用转义序列_0XXXX,其中XXXX是unicode字符代码。 $的字符代码为十六进制24,即转义序列为_00024,这意味着您的C ++函数名称变为Java_com_package_JNILib_00024Companion_getAppId

或者,您可以getAppId使用@JvmStatic添加JNILib静态方法Java_com_package_JNILib_getAppId。您的C ++函数名称应为JNIEnv *, jclass,参数为jclass(注意jobject而不是getAppId,因为 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Rechthoek { public partial class Form_Main : Form { int lengte = 0; int breedte = 0; Color Kleur = Color.Blue; int LijnDikte = 1; Point middelpunt = new Point(0, 0); public Form_Main() { InitializeComponent(); } private void Form_Main_Load(object sender, EventArgs e) { // } private void btn_uitkomst_Click(object sender, EventArgs e) { rechthoek rechthoek = new rechthoek(lengte, breedte, this, middelpunt, LijnDikte, Kleur); lbl_Omtrek.Text = lbl_Omtrek.Text + rechthoek.omtrek().ToString(); lbl_oppervlakte.Text = lbl_oppervlakte.Text + rechthoek.oppervlakte().ToString(); rechthoek.teken(); } private void txt_lengte_TextChanged(object sender, EventArgs e) { lengte = int.Parse(txt_lengte.Text); } private void txt_Breedte_TextChanged(object sender, EventArgs e) { breedte = int.Parse(txt_Breedte.Text); } private void btn_Kleur_Click(object sender, EventArgs e) { colorDialog1.ShowDialog(); Kleur = colorDialog1.Color; } private void txt_LijnDikte_TextChanged(object sender, EventArgs e) { LijnDikte = int.Parse(txt_LijnDikte.Text); } private void Form_Main_Click(object sender, EventArgs e) { middelpunt = e.Location; } } } 现在是一个类方法而不是实例方法)。