Step 1: Write the Java code
Create a Java class namedHelloWorld
That declares a native method. This class also includesmain
Method that createsHelloWorld
Object and callthe native method.
Step 2: Compile the Java code
Usejavac
To compile the Java code that you wrote inStep 1.
Step 3: Create the. h file
Usejavah
To create a JNI-style header file (.h
File) fromHelloWorld
Class. the header file provides a function signature for the implementation of the native
MethoddisplayHelloWorld
.
Step 4: Write the native method implementation
Write the implementation for the native method in a native language (such as ansi c) source file. The implementation will be a regular function that's integrated with your Java class.
Step 5: create a shared library
Use the C compiler to compile.h
File and.c
File that you created inSteps 3 and 4Into a shared library. in Windows 95/NT terminology, a shared library
Is called a dynamically loadable library (DLL ).
Step 6: run the program
And finally, usejava
, The Java interpreter, to run the program.
Package JNI;
Public class helloworld {
Public native void displayhelloworld ();
Static {
// System. loadlibrary ("hello ");
Runtime. getruntime (). loadlibrary ("hello ");
}
Public static void main (string [] ARGs ){
New helloworld (). displayhelloworld ();
}
}
# Include <JNI. h>
# Include "jni_helloworld.h"
# Include <stdio. h>
Jniexport void jnicall
Java_jni_helloworld_displayhelloworld (jnienv * ENV, jobject OBJ)
{
Printf ("Hello world! \ N ");
Return;
}