Saturday, April 24, 2021

How to cast uint8_t * to jbyteArray jni android

 I am working on an Android library that uses some c/c++ code.

I apparently have some sort of coding error that only happens to error out on runtime.

The error: JNI DETECTED ERROR IN APPLICATION: use of invalid jobject 0x7d61e62000.

jni android

This is the JNI code I am using to call the C code.

JNIEXPORT jbyteArray JNICALL

Java_com_comp_complibrary_api_initializeProduct(JNIEnv *env, jobject 

                                                    instance,

                                                    jbyteArray buffer_) {

    jbyte *buffer = env->GetByteArrayElements(buffer_, NULL);


    jbyteArray rv = (jbyteArray) initializeProduct((uint8_t *) buffer);


    env->ReleaseByteArrayElements(buffer_, buffer, 0);

    return rv;

}

initializeProduct returns a uint8_t *.

If I understand things correctly then I should be able to cast the return value to a jbyteArray and then be able to assign that to a byte[] in one of my java classes. However, this is not the case.

byte[] defend = (byte[]) initializeProduct(bufferByteArray);

You will notice that a jbyteArray can be cast to a uint8_t * as I am passing one in as a parameter to initializeProduct. Stepping through the c code I can confirm this to be true.

What is the correct way to convert/cast uint8_t * to jbyteArray?

Non sequitur. Just because you can cast something doesn't imply that it actually becomes that. You need to use GetByteArrayElements() or GetByteArrayRegion() to get the data out of the jbyteArray for your C code, followed by the appropriate ReleaseXXX() call when done.

No comments:

Post a Comment