java字符类型的返回值,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);

}

How do I get the string and convert it to a const char *?

My program crashes on the last line with access violation to 0x00000000. returnString is not NULL.

解决方案

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 a 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;".

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.

Add a

if (returnString == NULL)

return NULL;

after CallObjectMethod().

So look into the java source and see, whether the method getDESCDiagLayer() might return a null string.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值