Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 13: I/O, Applets, and Other Topics 305


After producing the necessary header file, you can write your implementation oftest( )
and store it in a file namedNativeDemo.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 includesjni.h, which contains interfacing information. This file is provided
by your Java compiler. The header fileNativeDemo.hwas created byjavahearlier.
In this function, theGetObjectClass( )method is used to obtain a C structure that has
information about the classNativeDemo. TheGetFieldID( )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 filejni.hfor
additional methods that handle other types of data.)
After creatingNativeDemo.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 tojni.hand its subordinate filejni_md.h.)


Cl /LD NativeDemo.c

This produces a file calledNativeDemo.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
Free download pdf