A Technology Blog About Code Development, Architecture, Operating System, Hardware, Tips and Tutorials for Developers.

Friday, July 9, 2010


5:18:00 PM Posted by Satish Kumar , , , 1 comment

Most of the native methods are written in "C". The mechanism to integrate "C" code with a Java program is called the Java Native Interface(JNI).

Java Client to call native method :

package org.satish.chapter_13;

public class NativeDemo {
    int i;
    public static void main(String[] args) {
        NativeDemo ob = new NativeDemo();
        ob.i = 10;
        System.out.println("This is ob.i before this native method : " + ob.i);
        System.out.println("This is ob.i after this native method : " + ob.i);
    public native void test();


Create headed file out of the Class :

Before to this compile the java to ".class" file. Now it is ready to create the ".h "file.

javah -jni org.satish.chapter_13.NativeDemo

Content of the header file :

/* DO NOT EDIT THIS FILE - it is machine generated */
/* Header for class org_satish_chapter_13_NativeDemo */

#ifndef _Included_org_satish_chapter_13_NativeDemo
#define _Included_org_satish_chapter_13_NativeDemo
#ifdef __cplusplus
extern "C" {
 * Class:     org_satish_chapter_13_NativeDemo
 * Method:    test
 * Signature: ()V
JNIEXPORT void JNICALL Java_org_satish_chapter_113_NativeDemo_test
  (JNIEnv *, jobject);

#ifdef __cplusplus

The C program : 

    This file contains the C version of the test()

#include "org_satish_chapter_13_NativeDemo.h"
JNIEXPORT void JNICALL Java_org_satish_chapter_113_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");
    i = (*env)->GetIntField(env, obj, fid);
    printf("i = %d\n",i);
    printf("Ending the native method.\n");

Create .SO file : 

Before to create the .so file, you need to install the gcc in your system.

sudo apt-get install gcc

Once gcc is installed, you can create the .so file using the following command.

sudo gcc -I /usr/lib/jvm/java-6-sun- -o NativeDemo.so -shared NativeDemo.c

Now your java class is ready to run and following is the output.

This is ob.i before this native method : 10
This is ob.i after this native method : 20
Starting the native method.
i = 10
Ending the native method.

1 comment: