Search code examples
javac++java-native-interface

Access array from Java-side


I have a method in a java class that is called to set a field of that class. The field is of type "char []. As I try and access an element of thechar []` my program will crash.

jni code:

mid = env->GetMethodID(cls,"setData","([C)V");
env->CallVoidMethod(obj,mid,MyClass.Data)   //MyClass.Data: unsigned char Data [8];

java code:

public void setData(char[] data2) {    //Data: char [] Data = new char [8];
    System.out.println("In Method");   //"In Method" is printed to console so
    //Data = data2.clone();              //i know im calling the method correctly
    for(int i = 0; i < 8; i++){
         Data[i] = data2[i];}
}

I have made it work, but only by changing up the signature of the method:

//jni side
mid = env->GetMethodID(cls,"setData","(CCCCCCCC)V");
env->CallVoidMethod(obj,mid,MyClass.Data[0],MyClass.Data[1],MyClass.Data[2],MyClass.Data[3],MyClass.Data[4],
    MyClass.Data[5],MyClass.Data[6],MyClass.Data[7]);

//java side
public void setData(char c1,char c2,char c3,char c4,char c5,char c6,char c7,char c8) {
    Data[0] = c1;
    Data[1] = c2;
    Data[2] = c3;
    Data[3] = c4;
    Data[4] = c5;
    Data[5] = c6;
    Data[6] = c7;
    Data[7] = c8;
}

How can I use the method with an array? Later in the program I have bigger arrays as fields and its much less messy to use one.


Solution

  • A java char array is not the same thing as a C char array:

    • a char array in Java is an object that includes the array length in addition to the data
    • a char in Java is 16 bits, typically twice the size of a char in C

    The jni API has functions for creating Java arrays and setting their elements: NewCharArray, GetCharArrayElements, and ReleaseCharArrayElements.