不熟悉c ++,有人可以帮助我将cmd
添加到myStr
数组并将其传递给main()
函数,这是我目前所拥有的:
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);
}
答案 0 :(得分:7)
好吧,在你完成它之前不要释放它。
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);
答案 1 :(得分:3)
为什么不利用对象来保证删除是自动完成的??
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;
};
然后:
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!