how to convert jobject to jstring
Asked Answered
N

1

6

I am trying to get a string in return to a function call from cpp to java.

This is my JNI call

 string GetIDJni()
{
    cocos2d::JniMethodInfo methodInfo;
    if (! JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, "GetID", "()Ljava/lang/String"))
    {
        return "";
    }

    jobject retObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID);
    jstring retStr = (jstring)retObj;
    methodInfo.env->DeleteLocalRef(methodInfo.classID);
    return (JniHelper::jstring2string(retStr));        
}

On compiling i get the error

error: invalid conversion from '_jobject*' to '_jstring*'

Can anyone please tell me how to solve this problem.

Neogene answered 26/12, 2012 at 4:28 Comment(0)
D
10

Here you go ...

const char* GetIDJni() {

    JniMethodInfo t;

        if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "GetIDJni", "()Ljava/lang/String;")) {
            jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
            t.env->DeleteLocalRef(t.classID);
            CCString *ret = new CCString(JniHelper::jstring2string(str).c_str());
            ret->autorelease();
            t.env->DeleteLocalRef(str);

            return ret->m_sString.c_str();
        }

        return 0;
    }

And if you want to get it return as std::String then

std::string GetIDJni() {
  std::string ret;
JniMethodInfo t;

    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "GetIDJni", "()Ljava/lang/String;")) {
        jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
        t.env->DeleteLocalRef(t.classID);
        ret=JniHelper::jstring2string(str);
        t.env->DeleteLocalRef(str);

        return ret;
    }

    return 0;
}
Dinge answered 26/12, 2012 at 9:47 Comment(1)
What did you differently, except for doing the casting on the same line with the function call?Zenobia

© 2022 - 2024 — McMap. All rights reserved.