After producing the necessary header file, you can write your implementation of test( )
and store it in a file named NativeDemo.c:
/* This file contains the C version of the
test() method.
*/
#include <jni.h>
#include "NativeDemo.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject obj)
{
jclass cls;
jfieldID fid;
jint i;
printf("Starting the native method.\n");
cls = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env, cls, "i", "I");
if(fid == 0) {
printf("Could not get field id.\n");
return;
}
i = (*env)->GetIntField(env, obj, fid);
printf("i = %d\n", i);
(*env)->SetIntField(env, obj, fid, 2*i);
printf("Ending the native method.\n");
}
Notice that this file includes jni.h, which contains interfacing information. This file is provided
by your Java compiler. The header file NativeDemo.h was created by javah earlier.
In this function, the GetObjectClass( ) method is used to obtain a C structure that has
information about the class NativeDemo. The GetFieldID( ) method returns a C structure
with information about the field named "i" for the class. GetIntField( ) retrieves the original
value of that field. SetIntField( ) stores an updated value in that field. (See the file jni.h for
additional methods that handle other types of data.)
After creating NativeDemo.c, you must compile it and create a DLL. To do this by using the
Microsoft C/C++ compiler, use the following command line. (You might need to specify the
path to jni.h and its subordinate file jni_md.h.)
Cl /LD NativeDemo.c
This produces a file called NativeDemo.dll. Once this is done, you can execute the Java
program, which will produce the following output:
This is ob.i before the native method: 10
Starting the native method.
i = 10
Ending the native method.
This is ob.i after the native method: 20
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home