Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a byte[] in Java to a function in C through JNI: how to use jarraybyte

This is the first time that I use the JNI and also the first time that I have to write some lines in C.

What I am trying to do is very simple. I'm just trying to switch the endiannes of a byte[] using a C routine.

In java it is done like this:

public void switchEndianness(byte[] array){

        byte byte1;
        byte byte2;

        for(int i = 0; i < array.length ; i+=2){
            byte1 = array[i];
            byte2 = array[i+1];

            array[i] = byte2;
            array[i+1] = byte1;
        }
}

So to do this using JNI, I've tried to imlpement the same routine in the JNICALL, but it doesn't compile. What I've written so far is this:

JNIEXPORT void JNICALL Java_CEndianness_switchEndianness(JNIEnv *env, jobject obj, jbyteArray array, jint offset, jint length){

    char byte1;
    char byte2;

    int i;
    for(i = offset; i  < length ; i+=2){
        byte1 = array[i];
        byte2 = array[i+1];

        array[i] = byte2;
        array[i+1] = byte1;
    }
}

I have no clue how to use the jbyteArray type of data. is it possible to store a jbyte in a char??? Another question is.. when this routine is over...will the byte[] in java be modified?? Or is it only modified inside the C call?

Any help???

Thanks to everybody!

like image 341
blutech Avatar asked Aug 06 '10 05:08

blutech


2 Answers

you can get jbyte* by GetByteArrayElements:

jbyte* bufferPtr = (*env)->GetByteArrayElements(env, array, NULL); 

And it is important to know the length of your array:

jsize lengthOfArray = (*env)->GetArrayLength(env, array); 

Having jbyte* and length, you can do all the things in c-array. Finally, releasing it:

(*env)->ReleaseByteArrayElements(env, array, bufferPtr, 0); 
like image 166
qrtt1 Avatar answered Sep 16 '22 23:09

qrtt1


qrtt has given you a great answer.

However, the JNI has very comprehensive and (relatively) easy-to-understand documentation that you should read front-to-back if you will be using JNI features again in the future. You can find it here: http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html

For your particular case, here's the section on dealing with arrays: http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html#wp1265

like image 22
Jason LeBrun Avatar answered Sep 17 '22 23:09

Jason LeBrun