Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jni convert string to char array

Not familiar with c++, can someone help me add cmd to the myStr array and pass it to the main() function, here is what I have so far:

JNIEXPORT void JNICALL Java_my_package_JNIActivity_callCmdLine(
    JNIEnv *env, jobject obj, jstring cmd)
{
    const char *nativeString = env->GetStringUTFChars(cmd, 0);
    env->ReleaseStringUTFChars(cmd, nativeString);

    char * myStr [] = {"v", nativeString};

    //int main(int argc, char *argv[])
    main(1, myStr); 
}
like image 933
user1159819 Avatar asked Feb 07 '12 16:02

user1159819


2 Answers

Well, don't release it before you're finished with it.

char * nativeString;

{    const char * _nativeString = env->GetStringUTFChars(cmd, 0);
     nativeString = strdup (_nativeString);
     env->ReleaseStringUTFChars(cmd, _nativeString);
}

char * myStr [] = {"v", nativeString};
main(1, myStr); 

free (nativeString);
like image 58
James McLaughlin Avatar answered Sep 28 '22 07:09

James McLaughlin


Why not taking advantage of objects to garantee deletion is done automatically...?

class ConvertStringHelper
{
public:
    ConvertStringHelper( JNIEnv *env, jstring value )
    {
        m_str = env->GetStringUTFChars(value, 0);
        m_value = &value;
        m_env = env;
    }
    ~ConvertStringHelper()
    {
        m_env->ReleaseStringUTFChars( *m_value, m_str);
    }

    jstring* m_value;
    const char *m_str;
    JNIEnv *m_env;
};

Then:

    ConvertStringHelper helper( env, cmd );
    const char* nativeStr = helper.m_str;
    // nativeStr is valid in helper's scope and memory will be cleanly released when exiting the scope!
like image 35
jpo38 Avatar answered Sep 28 '22 08:09

jpo38