Java Reference
In-Depth Information
Example 24-10 is a complete C native implementation. Passed an object of type HelloJni , it
increments the integer myNumber contained in the object.
Example 24-10. HelloJni.c
#include <jni.h>
#include "HelloJni.h"
#include <stdio.h>
/*
* This is the Java Native implementation of displayHelloJni.
*/
JNIEXPORT void
void JNICALL Java_HelloJni_displayHelloJni ( JNIEnv * env , jobject this ) {
jfieldID fldid ;
jint n , nn ;
( void
void ) printf ( "Hello from a Native Method\\n" );
iif ( this == NULL ) {
fprintf ( stderr , "'this.' pointer is null!\\n" );
return
return ;
}
iif (( fldid = ( * env ) -> GetFieldID ( env ,
( * env ) -> GetObjectClass ( env , this ), "myNumber" , "I" )) == NULL ) {
fprintf ( stderr , "GetFieldID failed" );
return
return ;
}
n = ( * env ) -> GetIntField ( env , this , fldid ); /* retrieve myNumber */
printf ( "\\"myNumber\\" value is %d\\n" , n );
( * env ) -> SetIntField ( env , this , fldid , ++ n ); /* increment it! */
nn = ( * env ) -> GetIntField ( env , this , fldid );
printf ( "\\"myNumber\\" value now %d\\n" , nn ); /* make sure */
return
return ;
}
Finally, you compile the C code into a loadable object. Naturally, the details depend on plat-
form, compiler, etc. For example, on Windows:
> set JAVA_HOME=C:\java # or wherever
> set INCLUDE=%JAVA_HOME%\include;%JAVA_HOME%\include\Win32;%INCLUDE%
> set LIB=%JAVA_HOME%\lib;%LIB%
> cl HelloJni.c -Fehello.dll -MD -LD
Search WWH ::




Custom Search