Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

java - How to convert jbyteArray to native char* in jni?

I am trying to convert a jbyteArray to native c string (char*) in jni? Unfortunately I can't find any documentation on how to do that. I'm invoking a java function with the following prototype in the c code.

public static byte[] processFile(byte[] p_fileContent)

In the c code I am invoking this function which is returning a byte array. The content of this byte array is a java string. But I need to convert it to a c string.

jbyteArray arr = (jbyteArray) env->CallObjectMethod(clsH, midMain, jb);
printf("%s
", (char*) arr);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe you would use GetByteArrayElements and ReleaseByteArrayElements. Something like:

boolean isCopy;
jbyte* b = GetByteArrayElements(env, arr, &isCopy);

You should be able to cast b to char* at this point in order to access the data in the array. Note that this may create a copy of the data, so you'll want to make sure to release the memory using ReleaseByteArrayElements:

ReleaseByteArrayElements(env, arr, b, 0);

The last parameter is a mode indicating how changes to b should be handled. 0 indicates that the values are copied back to arr. If you don't want to copy the data back to arr, use JNI_ABORT instead.

For more details see the JNI Reference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...