Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 952
iammilind Avatar asked Oct 18 '22 22:10

iammilind


1 Answers

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.

like image 86
marcinj Avatar answered Oct 21 '22 13:10

marcinj