Can't succeed in calling a Java function from a C++ module with JNI

时间:2018-06-04 16:51:21

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

I'm trying to call a Java class function from a C++ file using JNI and I always get a crash. My C++ file is :

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring

JNICALL
Java_MyPackage_MyApp_stringFromJNI(JNIEnv *env,jobject     /* this */,int a,jobject v) {
    jclass V = env->GetObjectClass(v);
    jmethodID setName=env->GetMethodID(V,"setName","(Ljava/lang/String;)V");
    env->CallVoidMethod(v,setName,"new name");
    return env->NewStringUTF("Testsss");
}

The problem arises when I try to call the method. In the logcat, I see this :

    runtime.cc:500] JNI DETECTED ERROR IN APPLICATION: use of deleted global reference 0x785cd7227ac6
runtime.cc:500]     from java.lang.String MyPackage.MyApp.stringFromJNI(int, MyPackage.V)
runtime.cc:500] "main" prio=5 tid=1 Runnable
runtime.cc:500]   | group="main" sCount=0 dsCount=0 flags=0 obj=0x73f2d670 self=0x785ceecbea00
runtime.cc:500]   | sysTid=7020 nice=-10 cgrp=default sched=0/0 handle=0x785cf3b94a08
runtime.cc:500]   | state=R schedstat=( 167686135 3959959 183 ) utm=14 stm=2 core=2 HZ=100
runtime.cc:500]   | stack=0x7ffe2c4fc000-0x7ffe2c4fe000 stackSize=8MB
runtime.cc:500]   | held mutexes= "mutator lock"(shared held)

The code for my Java function is :

void setName(String name) {
    this.name = name;
}

Any idea about what could be the root of the problem?

1 个答案:

答案 0 :(得分:0)

You can't call the method like that:

env->CallVoidMethod(v,setName,"new name");

You have to construct a Java string first, and then pass that:

jstring str = env->NewStringUTF("new name");
env->CallVoidMethod(v, setName, str);

Otherwise the VM tries to interpret the passed const char* as a global reference to a j.l.String. But it can't find it, so you get that error.

相关问题