开发者

JNI: How to get jbyteArray size

Background

I'm working with byte arrays in JNI. And I can't get length of jbyteArray. I'm writing code in eclipse in Windows 7.

Java code:

private native int Enroll( byte[] pSeed );

JNI code:

In JNI I have a struct that have two members unsigned long length and unsigned char data[1]

typedef struct blobData_s {
    unsigned long     length;
    unsigned char     data[1];
} blobData_t;

Now as my JNI function get as argument jbyteArray jpSeed i want to get the length of jpSeed and set it as length member of struct.

JNIEXPORT jint JNICALL Java_com_Test_Enroll( JNIEnv* env, jobject thiz, jbyteArray jpSeed ){
  开发者_如何学C   blobData_t* bd = malloc( sizeof(blobData_t) );
     bd->length = **Question 1**
     bd->data[1] = jbyteArray;
}

Question 1: How I can get the length of jpSeed in JNI ?

Question 2: Will this code works correct bd.data[1] = jbyteArray; ?


  1. You can use GetArrayLength(JNIEnv* env, jbyteArray array) Read here.

  2. Not sure what you want to do, I assume you want the content of jpSeed in bd.data[1]. Anyways, accessing the contents of a byte array, should be done with GetByteArrayElements(...).


Solution

Answer on Question 1. As jpSeed is jbyteArray it mean that you can get it's length by calling GetByteArrayElements( ... ) functions that declared in JNI ( you can read documentation here ) here the right code will be:

JNIEXPORT jint JNICALL Java_com_Test_Enroll( JNIEnv* env, jobject thiz, jbyteArray jpSeed ){
     blobData_t* bd = malloc( sizeof(blobData_t) );
     bd->length = (*env)->GetArrayLength( env, jpSeed );
     .......
}

Answer on Question 2. This bd->data[1] = jbyteArray; code is not correct as it will not be compiled the right solution for this part is:

JNIEXPORT jint JNICALL Java_com_Test_Enroll( JNIEnv* env, jobject thiz, jbyteArray jpSeed ){
     blobData_t* bd = malloc( sizeof(blobData_t) );
     .......
     jbyte* bytes = (*env)->GetByteArrayElements( env, jpSeed, 0 );
     bd->data[1] = bytes[1];
}

And don't forgot to release.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜