简体   繁体   中英

JNI dimensional array: passing 2D array from java to c

I am trying to achieve the following task.

  • Java file requests user to enter two numbers where both number are used to determine the number of rows and column of two dimensional array.

  • The two numbers are passed into native method.

  • In the native method, content of the array is created based on random character from A to Z.

  • Native method then passes the generated array back to the Java file.

  • Java file then display the content of the array.

I have coded the java function and also some of the c code. But my problem is on how to get the full length of the array since it is a 2D array. Using (*env)->GetArrayLength I get only the number of rows! But I don't know how to get the number of columns.

Java

import java.util.Scanner;

class Array { 
int num1, num2; 
native void DArray(char[][] Arr);

static { System.loadLibrary("CArray");}

public static void main(String args[]) { 
Scanner inp = new Scanner(System.in); 
Array obj = new Array();
System.out.printf("Enter the Number of rows: "); obj.num1 = inp.nextInt();
System.out.printf("Enter the shape <number>: "); obj.num2 = inp.nextInt();
char Arr[][] = new char[obj.num1][obj.num2];
obj.DArray(Arr);
}
}

C code (JNI)

#include <jni.h> 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

JNIEXPORT void JNICALL Java_Array_DArray (JNIEnv *env, jobject obj, jcharArray arr){

jsize len =(*env)->GetArrayLength(env, arr);

jchar Arr[len];
        for (int i=0;i<len;i++){
        Arr[i] = (rand()%26)+65;
        }       

        for (int i=0;i<len;i++){
            printf("%c""%c",Arr[i],' ');
        }       
return ;
}

First of all please understand that Java does not have a notion of two dimensional array. The best approximation is an array of 1 dimensional arrays but there is nothing in the language that will enforce same lengths for the nested arrays.

Second I believe that your assignment included creating of the array in native code not only filling it with random content.

I would probably pass two integers to my native method that would then use JNI functions NewObjectArray and NewCharArray to create the array of arrays, and fill it with random chars.

The native method would return this array to Java.

Printing has been covered extensively here: Java - Best way to print 2D array? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM