Issue
I need to send empty string from c++ to java and the java function should fill this string so the c++ could use it.
I dont want the Java code to return a value. I want it to fill a received String.
I thought using StringBuilder and this is how my java function looks like:
private static void setValue(StringBuilder param) {
param.append(value);
}
This is how my C++ code looks like:
jclass class = env->FindClass("class");
jmethodID method = env->GetStaticMethodID(class, "fillValue", "
(Ljava/lang/StringBuilder;)V");
What should i send to the function so it would work? I tried sending jstring but it doesnt work.
UPDATE: Tried the following code in c++ side but it didnt work:
char* str;
jstring string = env->NewStringUTF( str );
env->CallStaticObjectMethod(class,method, string);
const char* test = env->GetStringUTFChars(string, 0);
Solution
I would suggest using a byte[], which is a mutable type, instead of jumping through the hoops of creating a StringBuilder passing it, and then calling toString when you get it back. Or having problems with encoding.
You create a byte[] like this:
jclass mainClass = env->FindClass("Main");
jmethodID method = env->GetStaticMethodID(mainClass, "setValue", "([B)V");
jbyteArray bytes = env->NewByteArray(7);
env->CallStaticVoidMethod(mainClass, method, bytes);
const char* str = (char*) env->GetByteArrayElements(bytes, 0);
printf(str);
//... use here
env->ReleaseByteArrayElements(bytes, (jbyte*) str, JNI_ABORT);
And then you can fill it from Java like this:
public static void setValue(byte[] val) {
String someString = "Hello!"; // some string
byte[] bytes = someString.getBytes(StandardCharsets.US_ASCII);
System.arraycopy(bytes, 0, val, 0, bytes.length);
}
I realized later that you can also use a direct byte buffer, which is perhaps even simpler than using a byte[]. It allows you to create a Java usable view over an arbitrary block of bytes:
jmethodID method = env->GetStaticMethodID(mainClass, "setValue", "(Ljava/nio/ByteBuffer;)V");
const int buff_size = 1024;
char buff[buff_size]; // Creating a view over this block of memory
env->CallStaticVoidMethod(mainClass, method, env->NewDirectByteBuffer(buff, buff_size));
//... use buff
And in Java:
public static void setValue(ByteBuffer buff) {
String someString = "Hello!";
buff.put(someString.getBytes(StandardCharsets.US_ASCII));
}
Answered By - Jorn Vernee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.