JNI Android jbytearray for unsigned char * and vice versa

I have 2 separate pthread and one static struct array. One of pthread writes a decoding object that includes bytes, size, width, and height. another pthread actually looks at the stack and does some manipulation of the images and sends the result to the java function.

Here is the problem, on pthread1 I convert jbytearray to unsigned char * and save position 0 in a static array.

But when pthread2 comes in to convert it back to jbytearray, something happens and I always get a fatal signal.

This is the top of my cpp class

struct DecodeObject {

unsigned char* data;
int data_size;
int width;
int height;
int orientation;

};

static int decodeLimit = 200 ;
static DecodeObject decodeList[200] ;
static int decodeSize = -1 ;

Here is part of my pthread1

        //Values
        jbyteArray imageData = (jbyteArray) env->CallObjectMethod(decodeObject,getData);
        jint width = (jint) env->CallIntMethod(decodeObject,getWidth);
        jint height = (jint) env->CallIntMethod(decodeObject,getHeight);
        jint orientation = (jint) env->CallIntMethod(decodeObject,getOrientation);

        if(decodeSize<decodeLimit-1){

            DecodeObject object;
            object.data_size =   env->GetArrayLength (imageData);
            object.data = as_unsigned_char_array(env,imageData);
            object.width = width;
            object.height = height;
            object.orientation = orientation;

            decodeSize++;
            decodeList[decodeSize] = object;

        }
        else {
            LOGD("ERROR => BUFFER IS FULL");
        }

Here is part of my pthread2

        //PREPARE  RUNS OK
        LOGD("PREPARE"); // RUNS OK
        tempObject.data =  Prepare(tempObject.data,tempObject.width,tempObject.height);

        LOGD("CONVERT BACK TO JBYTEARRAY"); //HERE FAILS
        jbyteArray converted = as_byte_array(env,tempObject.data,tempObject.data_size);

        LOGD("DONE CONVERTING");

And finally, here is the function I use to convert

unsigned char* as_unsigned_char_array(JNIEnv* &env,jbyteArray array) {
    int len = env->GetArrayLength (array);
    unsigned char* buf = new unsigned char[len];
    env->GetByteArrayRegion (array, 0, len, reinterpret_cast<jbyte*>(buf));
    return buf;
}

jbyteArray as_byte_array(JNIEnv* &env,unsigned char* buf, jsize len) {

    jbyteArray array = env->NewByteArray(len);

    //HERE I GET THE ERROR, I HAVE BEEN TRYING WITH len/2 and WORKS , PROBABLY SOME BYTS ARE GETTING LOST.
    env->SetByteArrayRegion (array, 0, len, (jbyte*)(buf));

    return array;
}
+4

All Articles