I've used https://stackoverflow.com/a/38769851 and adapted for C++ as follows:
jsize num_bytes = env->GetArrayLength(message);
char *buffer = new char(num_bytes + 1);
if (!buffer) {
// handle allocation failure ...
//throw error?
return 1;
}
// obtain the array elements
jbyte* elements = env->GetByteArrayElements(message, NULL);
if (!elements) {
// handle JNI error ...
//throw error?
return 2;
}
// copy the array elements into the buffer, and append a terminator
memcpy(buffer, elements, num_bytes);
buffer[num_bytes] = 0;
std::string m(buffer, num_bytes + 1);
// Do not forget to release the element array provided by JNI:
env->ReleaseByteArrayElements(message, elements, JNI_ABORT);
I had to change char *buffer = malloc(num_bytes + 1);
to char *buffer = new char(num_bytes + 1);
because of C++ errors. Why it won't work in C++ by the way?
Well, so with this code I get a crash. I think it's probably related to this change I made, because env->ReleaseByteArrayElements(message, elements, JNI_ABORT);
might be releasing it as if it were allocated by malloc
.
How should this code in C++ work?