Jni convert string to char array

Not familiar with C ++, can anyone help me add cmd to myStr array and pass it to main() function, here is what I still have:

 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); } 
+4
source share
2 answers

Well, don't let him go before you're done with him.

 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); 
+6
source

Why not take advantage of the facilities to guarantee removal, performed 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 scope and memory will be cleanly released when exiting the scope! 
+2
source

Source: https://habr.com/ru/post/1395272/


All Articles