我需要通过 JNI 将字符串列表从 Java 传递到 C。 我的 Java 程序传递一个 List 参数,而 C 程序接受一个列表。
下面是我尝试过的代码。
JNIEXPORT jobject JNICALL Java_jni_CallJNIfunction(JNIEnv *env,
jobjectArray jParameters){
list<const char*> cParameters;
jsize stringCount = env->GetArrayLength(jParameters);
for (int i=0; i<stringCount; i++) {
jstring arrElement = (jstring) (env->GetObjectArrayElement(jParameters, i));
const char* nativeElement = env->GetStringUTFChars( arrElement, NULL);
cParameters.push_back(nativeElement);
env->ReleaseStringUTFChars(arrElement, nativeElement);
}
CallCfunction(cParameters);
}
但是我的 JVM 在 GetStringUTFChars() 行崩溃了。 这个程序有什么问题?
最佳答案
你会:
const char* nativeElement = env->GetStringUTFChars( arrElement, NULL);
cParameters.push_back( nativeElement );
env->ReleaseStringUTFChars(arrElement, nativeElement);
您释放了存储到列表中的字符串,因此您的列表包含很多坏指针!
您必须将字符串复制到一个长时间分配的空间中,您可以选择 std::string、char*+malloc 或使用后忘记的方法。
第三种解决方案的说明:
for( int i = 0; i < stringCount; ++i )
{
jstring arrElement = (jstring) (env->GetObjectArrayElement(jParameters, i));
const char* nativeElement = env->GetStringUTFChars( arrElement, NULL);
CallCfunction( nativeElement ); // modified to process an item not a list<
env->ReleaseStringUTFChars(arrElement, nativeElement);
}
关于java - 将字符串列表从 Java 传递到 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12907685/