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

There is a C ++ function that is called from Java code through JNI.
I want to pass the base c-string correctly in Java, so I did the following:

// 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 data() function ceases to be thread safe.
What is the best way to achieve thread safety when passing a string without any undefined actions?

+5
source share
1 answer

I want to pass the base c-string to the correct Java

How do you pass a C ++ string in java? You cannot pass a C ++ bare pointer in java, you must use jni functions for this, i.e.:

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

and then pass jstr to java or pass as a java array. This function duplicates the string, so there are no thread safety issues.

If you want to split the memory area between java nad C ++, you can try the following jni functions: NewDirectByteBuffer, GetDirectBufferAddress, GetDirectBufferCapacity.

+3
source

Source: https://habr.com/ru/post/1236123/


All Articles