简体   繁体   English

无法使用JNI从C ++模块调用Java函数

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

I'm trying to call a Java class function from a C++ file using JNI and I always get a crash. 我试图使用JNI从C ++文件中调用Java类函数,但我总是崩溃。 My C++ file is : 我的C ++文件是:

#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 : 在logcat中,我看到了:

    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 : 我的Java函数的代码是:

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

Any idea about what could be the root of the problem? 是否知道可能是问题的根源?

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: 您必须先构造一个Java字符串,然后传递该字符串:

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 jlString . 否则,VM尝试将传递的const char*解释为对jlString的全局引用。 But it can't find it, so you get that error. 但是找不到它,所以您会收到该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM