调用静态JNI方法从C ++返回一个String [英] call a static JNI method to return a String from C++

查看:327
本文介绍了调用静态JNI方法从C ++返回一个String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Android中调用以下java方法

I am trying to call the following java method in Android

public static String getLevelFile(String levelName) { /*body*/}

使用以下jni代码

JniMethodInfoJavaApi methodInfo;

    if (! getStaticMethodInfo(methodInfo, "getLevelFile", "(Ljava/lang/String;)Ljava/lang/String;"))
        {
            return std::string("");
        }
    LOGD("calling getLevelFile");
    jstring returnString = (jstring) methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, levelName.c_str());
    LOGD("returned from getLevelFile");
    methodInfo.env->DeleteLocalRef(methodInfo.classID);

    const char *js = methodInfo.env->GetStringUTFChars(returnString, NULL);
    std::string cs(js);
    methodInfo.env->ReleaseStringUTFChars(returnString, js);
    LOGD("returning Level data");

当执行 CallStaticMethodObject()。我已通过使用 javap 验证了方法签名是正确的。和 LOGD(调用getLevelFile); 打印罚款,然后它崩溃。我可以做同样的类,但不是这个其他 CallStaticVoidMethod() s。

The app crashes when doing the CallStaticMethodObject() . I have verified that the method signature is correct by using javap. And the LOGD("calling getLevelFile"); prints fine and then it crashes. I am able to do other CallStaticVoidMethod()s from the same class but not this one. Any ideas what I am doing wrong?

推荐答案

您不能直接传递一个nul终止的字符串(从 c_str())作为Java / JNI方法的参数。

You can't directly pass a nul terminated string (returned from c_str()) as a parameter to a Java/JNI method.

要传递给方法, (例如使用 NewStringUTF )从$ n> $ c> jstring 。

To pass it to the method, create a jstring from the nul terminated string (for example using NewStringUTF) and pass that instead.

这篇关于调用静态JNI方法从C ++返回一个String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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