The JNI equivalent of an array is jarray. To access an array from a Java program in a C program, you must copy the array into a buffer defined in the C program. The JNI provides two methods that enable you to access arrays from a Java program in C:
Get<type>ArrayRegion: Copies the contents of an array into a buffer.
Set<type>ArrayRegion: Copies the contents of a buffer into an array.
For example, to copy the contents of an integer array, n, with 10 elements into a buffer, buf, you need to include the following in the C code:
(*exeenv)->GetIntArrayRegion(exeenv, n, 0, 10, buf)
class ArrayDemo
{
private native void disArray(int[] n);
public static void main(String[] args)
{
ArrayDemo dem = new ArrayDemo();
//Initializing the array
int n[] = {45,78,35,34,65,32,98,11,3,67};
//Invoking the native method
dem.disArray(n);
}
static
{
//Loading the library
System.loadLibrary("ArrayDemo_lib");
}
}
Following code shows how the header file that corresponds to the ArrayDemo class file is generated.
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class ArrayDemo */
#ifndef _Included_ArrayDemo
#define _Included_ArrayDemo
#ifdef __cplusplus
extern "C"
{
#endif
/*
* Class: ArrayDemo
* Method: disArray
* Signature: ([I)V
*/
JNIEXPORT void JNICALL Java_ArrayDemo_disArray (JNIEnv *, jobject, jintArray);
#ifdef __cplusplus
}
#endif
#endif
Implementation of the disArray Method
#include <stdio.h>
#include <jni.h>
#include "ArrayDemo.h"
JNIEXPORT void JNICALL
Java_ArrayDemo_disArray(JNIEnv *exeenv, jobject javaobj, jintArray n)
{
jint *buf;
jint i;
printf("Printing the values of the array in C\n");
//Storing the elements of the array in a buffer
buf = (*exeenv)->GetIntArrayElements(exeenv, n, NULL);
if (buf == NULL)
{
return; /* exception occurred */
}
for (i=0; i<10; i++)
{
//Printing the array elements
printf("%d\n",buf[i]);
}
(*exeenv)->ReleaseIntArrayElements(exeenv, n, buf, 0);
}
Next Article:- How To Use Java Strings In C?


Currently Active Users
Categories
Latest Blog Entries

Rate this article