Spod
Spod

Reputation: 13

2D C Arrays in JNI

When I fill this 2d array called map[][] and try to print out all the values stored in it I get a null character after each actual array character. This shouldn't be the case, I would like all characters in the mapFromJava array to be in the same layout in the map variable.

 JNIEXPORT void JNICALL Java_CGameLogic_fillMap(JNIEnv *env, jobject thisObj, jobjectArray mapFromJava) 
 {
      jsize len1 = (*env)->GetArrayLength(env, mapFromJava);
      int i;
      for(i=0; i<len1; i++) {
          jcharArray array = (*env)->GetObjectArrayElement(env,mapFromJava, i);
          int len2 =(*env)->GetArrayLength(env, array);
          jchar *mapArray = (*env)->GetCharArrayElements(env, array, 0);
          int size =  (sizeof(jchar) * len2);
          memcpy(map[i], mapArray, size);
     }
}

map is a 2d char array. This is the print function:

    JNIEXPORT void JNICALL Java_CGameLogic_printMap(JNIEnv *env, jobject thisObj, jint mapHeight, jint mapWidth) {
int y;
int x;
for (y = 0; y < mapHeight; y++) {
    for (x = 0; x < mapWidth; x++) {
        printf("%c", map[y][x]);
    }
    printf("\n");
}

}

Upvotes: 1

Views: 224

Answers (1)

bodangly
bodangly

Reputation: 2624

I do not know how you determined there are extra null bytes, but keep in mind a jchar is a 16 bit value as java characters are UTF-16. That means characters in the ASCII range will consist of a null byte and the ASCII byte.

Update Your output should be stored as wchar_t not char as a jchar is a 16 bit value and a C char is 8 bits.

Upvotes: 1

Related Questions