JNI: How to get jbyteArray size

Background

I work with byte arrays in JNI . And I can not get the length of jbyteArray . I am writing code in eclipse on Windows 7 .

Java code:

private native int Enroll( byte[] pSeed ); 

JNI Code:

In JNI, I have a structure consisting of two members unsigned long length and unsigned char data[1]

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

Now that my JNI function receives the jbyteArray jpSeed argument, I want to get the length of jpSeed and set it as a member of the length of the structure.

 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 can I get jpSeed length in JNI?

Question 2. Does this code work bd.data[1] = jbyteArray; ?

+6
source share
2 answers
  • You can use GetArrayLength(JNIEnv* env, jbyteArray array) Read here . p>

  • Not sure what you want to do, I assume that you want the contents of jpSeed in bd.data[1] . In any case, access to the contents of the byte array should be done using GetByteArrayElements(...).

+24
source

Decision

The answer to question 1 .. Since jpSeed is jbyteArray , this means that you can get its length by calling the GetByteArrayElements( ... ) functions declared in JNI (you can read the documentation here ) here the correct 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 to question 2. This code is bd->data[1] = jbyteArray; invalid because it will not be compiled. The correct solution for this part:

 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 do not forget to free.

+3
source

Source: https://habr.com/ru/post/889928/


All Articles