将字符串数组发送到Android中的本机代码

时间:2018-07-16 19:12:59

标签: android android-ndk

我从C++的{​​{1}}中调用一个函数。在java中,有一个java数组,我想在Strings函数中使用。

我在C++中有

C++

实现我想要的最简单的方法是什么?当我尝试这种方法和其他变体时,它会崩溃或产生废话数据。

1 个答案:

答案 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 变体。