java JNI 字符串返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15268426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JNI String return value
提问by Salvatore
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:
我有一个 Java 实例方法,它返回一个字符串,我在 C++ 中通过 JNI 调用这个方法。我编写了以下代码:
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);
}
How do I get the string and convert it to a const char *?
如何获取字符串并将其转换为 const char *?
My program crashes on the last line with access violation to 0x00000000. returnString is not NULL.
我的程序在最后一行崩溃,访问冲突为 0x00000000。returnString 不是 NULL。
回答by Olaf Dietsche
According to GetStringUTFChars
, the last parameter is a pointer to jboolean
.
根据GetStringUTFChars
,最后一个参数是指向 的指针jboolean
。
Change
改变
return env->GetStringUTFChars(returnString, JNI_FALSE);
to
到
return env->GetStringUTFChars(returnString, NULL);
Or better yet, return a std::string
或者更好的是,返回一个 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.
虽然,有两个可能的错误来源。
The first one is the method signature. Try "()Ljava/lang/String;"
instead of "(Ljava/lang/Object;)Ljava/lang/String;"
.
第一个是方法签名。尝试"()Ljava/lang/String;"
代替"(Ljava/lang/Object;)Ljava/lang/String;"
.
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.
第二个在 java 源代码中。如果 java 方法返回空字符串,CallObjectMethod()
将返回 NULLjstring
并GetStringUTFChars()
失败。
Add a
添加一个
if (returnString == NULL)
return NULL;
after CallObjectMethod()
.
之后CallObjectMethod()
。
So look into the java source and see, whether the method getDESCDiagLayer()
might return a null string.
因此,查看 java 源代码并查看该方法是否getDESCDiagLayer()
可能返回空字符串。