我想從java函數中的C函數顯示來自二維char數組的5x5字符網格。我目前使用的代碼返回一個正確的5x5網格,但網格中的所有字符都顯示爲空或隨機符號。我使用以構建被返回數組的代碼如下:從C函數返回二維字符數組到Java JNI
JNIEXPORT jobjectArray JNICALL Java_MapJNI_look(JNIEnv *env, jobject jObject, jint x, jint y){
initializeMap();
jobjectArray lookRow[5];
char lookChars[5][5];
char *arrayPointer;
int i, j, k, l;
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
int posX = x + j - 5/2;
int posY = y + i - 5/2;
if(posX >= 0 && posX < getMapWidth() && posY >= 0 && posY < getMapHeight()){
lookChars[i][j] = map[posY][posX]; //todo check this is correct
}else{
lookChars[i][j] = 'X';
}
}
arrayPointer = &lookChars[i][j];
//Setting an element of the row array object to a particular sequence of map characters
//5 represents the 5x5 look window
lookRow[i] = createArrayRow(env, 5, arrayPointer);
}
//Creating an array that contains all the rows for the look window
//Any element of lookRow[] is valid when obtaining the class through GetObjectClass
jobjectArray rows = (*env)->NewObjectArray(env, 5, (*env)->GetObjectClass(env, lookRow[0]), 0);
for(k = 0; k < 5; k++){
(*env)->SetObjectArrayElement(env,rows,k, lookRow[k]);
}
return rows; }
的initializeMap()函數簡單地填充與2D char數組'。字符。 createArrayRow()函數如下:
static jobjectArray createArrayRow(JNIEnv *env, jsize count, char* elements){
//Storing the class type for the object passed
jclass stringClass = (*env)->FindClass(env, "java/lang/String");
//Creating a jobjectArray out of the supplied information
//This creates an array that can be passed back to java
jobjectArray row = (*env)->NewObjectArray(env, count, stringClass, 0);
jsize i;
//Assigning each element of the newly created array object to a specific string
(*env)->SetObjectArrayElement(env, row, i, (*env)->NewStringUTF(env, elements));
return row; }
如果您有任何建議,他們將不勝感激,謝謝。
在C中,如果'rows'是一個數組,就像註釋所說的那樣,'returns rows;'只返回一個指針而不是一個數組,返回一個現在無效的對象。建議使用完整的最小代碼示例來複制此問題, – chux