JNI字符串返回值 [英] JNI String return value

查看:122
本文介绍了JNI字符串返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回一个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.

推荐答案

根据更改

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字符串返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆