Previous | Next | Trail Map | Using the JNI | Step By Step

Step 4: Write the Native Method Implementation

Now, you can finally write the implementation for the native method in a language other than the Java programming language.

The function that you write must have the same function signature as the one generated by javah in the HelloWorld.h file in Step 3: Create the .h File. Recall that the function signature generated for the HelloWorld class's displayHelloWorld() native method looks like this:

JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *, jobject);
Here's the C language implementation for the native method Java_HelloWorld_displayHelloWorld(). This implementation is in the file named HelloWorldImp.c.
#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>

JNIEXPORT void JNICALL 
Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj) 
{
  printf("Hello world!\n");
  return;
}
The implementation for Java_HelloWorld_displayHelloWorld() is straightforward. The function uses the printf() function to display the string "Hello World!" and then returns.

This file includes three header files:


Previous | Next | Trail Map | Using the JNI | Step By Step