我从C++
的{{1}}中调用一个函数。在java
中,有一个java
数组,我想在Strings
函数中使用。
我在C++
中有
C++
实现我想要的最简单的方法是什么?当我尝试这种方法和其他变体时,它会崩溃或产生废话数据。
答案 0 :(得分:1)
JNI主要是一个C API,它对std::string
一无所知,因为您可以通过在包含本机方法声明的Java源文件上调用 javah 来进行验证。>
Java也不是C,因此无需将数组大小作为附加参数传递。
因此您的native void updateStandingBoard(String[] result, int size)
实际上应该是native void updateStandingBoard(String[] result)
请记住,JNI代码应为
std::vector<std::string> names; // much safer or use std::array as alternative
extern "C"
JNIEXPORT void JNICALL
Java_com_erikbylow_mycamera3_JNIUtils_updateStandingBoard(JNIEnv *env, jobject type, jobjectArray names) {
jint nbrElements = env->GetArrayLength(names);
// now copy the strings into C++ world
for (int i = 0; i < nbrElements ; i++) {
// access the current string element
jobject elem = env->GetObjectArrayElement(names, i);
jsize length = env->GetStringLength(elem);
// pin it to avoid GC moving it around during the copy
const jchar *str = env->GetStringChars(elem, nullptr);
names.push_back(std::string(str, length));
// make it available again to the VM
env->ReleaseStringChars(elem, str);
}
}
这只是用于基本字符串,如果您对UTF字符串感兴趣,则应使用上述JNI函数的std::wstring
和 UTF 变体。