Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ){
     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; ?

like image 628
Viktor Apoyan Avatar asked Jun 07 '11 08:06

Viktor Apoyan


2 Answers

  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(...).

like image 104
Naytzyrhc Avatar answered Sep 28 '22 07:09

Naytzyrhc


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.

like image 23
Viktor Apoyan Avatar answered Sep 28 '22 06:09

Viktor Apoyan