0

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.

1
  • A Java char holds one UTF-16 code unit, which can be a whole or half of a Unicode codepoint. Not all 16-bit values are allowed. So, be careful what you stuff into a Java char array. It might be better to work with a Java string. The string constructor takes an array of bytes and a character set/encoding argument. If what you really want is a buffer to hold arbitrary binary data, there are special classes for that, but if you do use a string, convert from the IBM437 character set because it allows all 256 bytes values and is round-trippable with a Java string. Commented Jul 25, 2013 at 16:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! couldn't have given a better answer!
That's right. A Java char corresponds to a C++ char16_t. jni.h was doesn't define it that way because it was designed for C and older C++. Still that's what was meant and documented all along.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.