问题
I want to access an array from JNI to Java (By creation of shared library libtest.so
file)
I'm doing it as below:
JNI Code (C)
int size = 5; /* Array Size */
char sample_arr[size] = {1, 2, 3, 4, 5}; /* Array to be accessed in Java */
jbyteArray result_arr = (*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, result_arr, 0, size, sample_arr);
jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "(I)V");
(*env)->CallVoidMethod(env, obj, mid, get_event);
I believe that jbyte in JNI is char equivalent.
The above code is compiled to form a Shared Object libtest.so
.
Java Code
public class Callbacks
{
char result_arr[];
public void Callbacks() {
System.loadLibrary("test"); /* Load the Shared Object */
}
public void callback(int get_event)
{
....
Log.d(TAG, "Received Array at Java: result_arr[] : "+Arrays.toString(result_arr));
....
}
}
Output
D/[JNI] (3106): Recieved Array at Java: result_arr[] : null
The output should be: 1, 2, 3, 4, 5
but I'm getting null
Is this the right way of accessing the array ?
Please point out any mistake.
I'm new to java, and a beginner at JNI. Proficient with C though.
I would appreciate any help on this.
回答1:
How exactly did you send the result_arr array from JNI back to Java? I am not sure what the get_event argument is suppose to be, but it is definitely not a reference to result_arr. You should do 1 of two things: A) Add a second argument to the callback and pass result_arr back to Java, OR B) Set the Callbacks.result_arr instance variable from JNI buy acquiring the class and then getting the field ID for that class. If you would like more assistance, you will need to post more complete code.
来源:https://stackoverflow.com/questions/24991970/passing-an-array-from-jni-to-java