Step By Step |
Now, you can finally get down to the business of writing the implementation for the native method in another language.The function that you write must have the same function signature as the one you generated with
javah
into theHelloWorld.h
file in Step 3: Create the .h File. The function signature generated for theHelloWorld
class'sdisplayHelloWorld()
native method looks like this:Here's the implementation forJNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *, jobject);Java_HelloWorld_displayHelloWorld()
, which is in the file namedHelloWorldImp.c
.The implementation for#include <jni.h> #include "HelloWorld.h" #include <stdio.h> JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj) { printf("Hello world!\n"); return; }Java_HelloWorld_displayHelloWorld()
is straightforward: the function uses theprintf()
function to display the string "Hello World!" and then returns.This file includes three header files:
jni.h
, which provides information the native language code requires to interact with the Java runtime system. When writing native methods, you must always include this file in your native language source files.- The
.h
file that you generated in Step 3: Create the .h File.- The code snippet above also includes
stdio.h
because it uses theprintf()
function.
Step By Step |