17

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\n", (char*) arr);
John
  • 941
  • 8
  • 17
Sid
  • 523
  • 1
  • 5
  • 18

1 Answers1

25

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
DRH
  • 7,868
  • 35
  • 42
  • @DRH Updating a 1.4.2 link to a 1.5 link isn't much of an improvement. – user207421 Nov 29 '16 at 02:32
  • 2
    Careful will null termination. In general, file contents won't be null terminated; C(++) string functions might choke on that. In order to reliably work around that, you'd have to copy the file bytes into a buffer one byte larger, and set the final byte to zero – Seva Alekseyev Nov 29 '16 at 02:35
  • `ReleaseByteArrayElements()` must be called even if there was no copy operation involved – Alex Cohn Oct 16 '19 at 18:38
  • I used this way but the size of jbyte is very lower than the jbytearray element. For example arr size is 16384 but when I convert it to jbyte the size of jbyte is 8. Anyone has a idea about it? – Fahime Ghasemi Sep 01 '22 at 15:41