Java – JNI string return value
I have a Java instance method that returns a string. I call this method through JNI in C I wrote 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);
}
How do I get a string and convert it to const char *?
My program crashed on the last line with an access violation of 0x00000000 Returnstring is not null
Solution
According to getstringutfchars, the last parameter is a pointer to jboolean
change
return env->GetStringUTFChars(returnString,JNI_FALSE);
to
return env->GetStringUTFChars(returnString,NULL);
Or better yet, return an 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 code, which seems good so far
Although, there are two possible sources of error
The first is method signature Try "() ljava / Lang / string;" Instead of "(ljava / Lang / object;) Ljava / lang / String;”.
The second is the Java source code itself If the Java method returns an empty string, callobjectmethod() will return null jstring and getstringutfchars() will fail
Add a
if (returnString == NULL)
return NULL;
After callobjectmethod()
So check the Java source code to see if the method getdescdiaglayer () can return an empty string
