Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert jobject to jstring

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.

like image 976
glo Avatar asked Dec 26 '12 04:12

glo


1 Answers

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;
}
like image 50
user1169079 Avatar answered Sep 17 '22 14:09

user1169079