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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With