简体   繁体   中英

How to pass a C++ string to Java JNI in a well defined thread-safe way?

There is a C++ function, which is called from Java code via JNI.
I want to pass the underlying c-string to the Java correctly, so I have done below arrangements:

// main.cpp
string global;

const char* data ()  // Called externally by JNI
{
  return (global = func_returning_string()).data();  // `.data()` = `.c_str()`
}

But in this case, the function data() is no longer thread-safe.
What is the best way to achieve the thread-safety while passing the string without causing any undefined behavior?

I want to pass the underlying c-string to the Java correctly

How are you passing c++ string to java? You cant pass bare c++ pointer to java, you should use jni functions for that, ie.:

jstring jstr = (*env)->NewStringUTF(env, data());

and then pass jstr to java, or pass in the form of an java array. This function duplicates string so there is no problem with thread safety.

If you want to share memory region between java nad c++ then you might try with following jni functions: NewDirectByteBuffer, GetDirectBufferAddress, GetDirectBufferCapacity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM