JNI回调时出错

时间:2017-07-27 09:08:03

标签: java android c++ java-native-interface

我正在研究JNI回拨

  • 我需要从cpp调用java

我在cpp中的示例代码如下

JNIEXPORT jstring JNICALL
Java_com_example_arjunh_myapplication_MainActivity_getJniString(JNIEnv *env, jobject instance) {

jstring jstr = env->NewStringUTF("This string comes from JNI");

jclass clazz = env->FindClass("MainActivity");  // Error at this line

jmethodID messageMe = env->GetMethodID(clazz, "messageMe", "(Ljava/lang/String;)V");


jobject result = env->CallObjectMethod(instance, messageMe, jstr);

const char* str = env->GetStringUTFChars((jstring) result, NULL);
printf("%s\n", str);

env->ReleaseStringUTFChars(jstr, str);


return env->NewStringUTF("Hello from JNI!");
}

我的java类如下(MainActivity)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    btnAdd = (Button) findViewById(R.id.btnAdd);
    tv = (TextView) findViewById(R.id.sample_text);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            getJniString();

        }
    });

}


public void messageMe(String text) {

    tv.setText(text);

}

错误是

 ClassNotFoundException: Didn't find class "MainActivity" on path: DexPathList[[zip file "/data/app/com.example.arjunh.myapplication-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.arjunh.myapplication-1/lib/arm64, /data/app/com.example.arjunh.myapplication-1/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]

如何推荐班级

jclass clazz = env-> FindClass(" MainActivity");

1 个答案:

答案 0 :(得分:2)

我认为您应该将包名称指定为documentation suggest

  

name:一个完全限定的类名(即包名,分隔   按“/”,后跟类名)。如果名称以“[”开头(   数组签名字符),它返回一个数组类。字符串是   以修改后的UTF-8编码。

jclass clazz = env->FindClass("your/package/name/MainActivity")