问题描述
我有一个返回一个String的Java实例方法,我正在C ++中通过JNI调用此方法.我编写了以下代码:
I have a Java instance method which returns a String and I'm calling this method through JNI in C++. I have written the following code:
const char *DiagLayerContainer_getDESC(JNIEnv *env, jobject diagLayer) {
jclass diagLayerClass = env->FindClass(PARSER_CLASS);
jmethodID getDESCDiagLayerMethodID = env->GetMethodID(diagLayerClass, "getDESCDiagLayer", "(Ljava/lang/Object;)Ljava/lang/String;");
jstring returnString = (jstring) env->CallObjectMethod(diagLayer, getDESCDiagLayerMethodID);
return env->GetStringUTFChars(returnString, JNI_FALSE);
}
如何获取字符串并将其转换为const char *?
How do I get the string and convert it to a const char *?
我的程序在访问冲突为0x00000000的最后一行崩溃. returnString不是NULL.
My program crashes on the last line with access violation to 0x00000000. returnString is not NULL.
推荐答案
根据 GetStringUTFChars
,最后一个参数是指向jboolean
的指针.
更改
return env->GetStringUTFChars(returnString, JNI_FALSE);
到
return env->GetStringUTFChars(returnString, NULL);
或者更好的是,返回std::string
std::string DiagLayerContainer_getDESC(...) {
...
const char *js = env->GetStringUTFChars(returnString, NULL);
std::string cs(js);
env->ReleaseStringUTFChars(returnString, js);
return cs;
}
我已经建立了一个类似的简单示例,并且到目前为止,代码看起来还不错.
I've built a similar simple example and the code as is, seems fine so far.
尽管有两种可能的错误源.
Although, there are two possible error sources.
第一个是方法签名.尝试使用"()Ljava/lang/String;"
代替"(Ljava/lang/Object;)Ljava/lang/String;"
.
The first one is the method signature. Try "()Ljava/lang/String;"
instead of "(Ljava/lang/Object;)Ljava/lang/String;"
.
第二个在Java源代码本身中.如果java方法返回空字符串,则CallObjectMethod()
将返回NULL jstring
,而GetStringUTFChars()
失败.
The second one is in the java source itself. If the java method returns a null string, CallObjectMethod()
will return a NULL jstring
and GetStringUTFChars()
fails.
添加
if (returnString == NULL)
return NULL;
在CallObjectMethod()
之后.
因此,请查看java源代码,看看方法getDESCDiagLayer()
是否可能返回空字符串.
So look into the java source and see, whether the method getDESCDiagLayer()
might return a null string.
这篇关于JNI字符串返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!