user3807476
user3807476

Reputation: 47

android ndk - cast jchar* to char*

why when casting jchar* to char* , c++ add a zero between each array element ?

java :

public char[] mychar;
 .
 .
 
mychar = new char[3];

mychar[0] = 10;
mychar[1] = 20;
mychar[2] = 30;

c++ :

Java_com_example_bb_mainact_getchar(JNIEnv *env, jobject thiz) {


    jclass cls = env->GetObjectClass(thiz);
    jfieldID fieldId = env->GetFieldID(cls, "mychar", "[C");
    jobject objArray = env->GetObjectField (thiz, fieldId);

    jcharArray* chArray = reinterpret_cast<jcharArray*>(&objArray);
    jchar *data = env->GetCharArrayElements(*chArray, 0);        
        
    LOGI( "data[0]: %d",  data[0]);  // --> 10
    LOGI( "data[1] : %d",  data[1]);  // --> 20
    LOGI( "data[2] : %d",  data[2]);  // --> 30

    char* data2 = reinterpret_cast<char *>(data);

    LOGI( "data2[0] : %d",  data2[0]);  // --> 10
    LOGI( "data2[1]: %d",  data2[1]);  // --> 0
    LOGI( "data2[2]: %d",  data2[2]);  // --> 20
         
     .

why when cast from jchar* to char* c++ make array like this ? {10 , 0 , 20 , 0 , 30}

Upvotes: 0

Views: 201

Answers (1)

Michael
Michael

Reputation: 58447

jchar is a 16-bit type. char is usually an 8-bit type.

You could fix this e.g. by treating data as a pointer to a bunch of 16-bit elements, or by using a byte[] instead of a char[] on the Java side.

Upvotes: 1

Related Questions