« » How to use native functions in Java on Mac OS X

Thursday 27th of August, 2009 by Torgeir Filed under code and Java No comments

Here's one for the geeks, on how to use native functions in Java on Mac OS X. Start out by creating Java a class

public class NativeSum {}

In your class, declare a native method you will implement in c

public native static int nativeSum(int a, int b);

Load your c library, which we will create later on

static {
    System.loadLibrary("nativesum");
}

Make use of your native c function to calculate the sum of the numbers 10 and 20

public static void main(String[] args) {
    int c = nativeSum(10, 20);
    System.out.println(c);
}

By now you should have a Java class similar to the following

public class NativeSum {

    public native static int nativeSum(int a, int b);

    static {
        System.loadLibrary("nativesum");
    }

    public static void main(String[] args) {
        int c = nativeSum(10, 20);
        System.out.println(c);
    }
}

Compile your java class

$ javac NativeSum

Run the javah command to generate a JNI c header file

$ javah -jni NativeSum

This will generate something like the this as a NativeSum.h c header file

/* DO NOT EDIT THIS FILE - it is machine generated */
#include 
/* Header for class NativeSum */

#ifndef _Included_NativeSum
#define _Included_NativeSum
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     NativeSum
 * Method:    nativeSum
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_NativeSum_nativeSum
  (JNIEnv *, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

Now create a NativeSum.c file to hold your c implementation of the NativeSum.h header file's method, like this

#include 

JNIEXPORT jint JNICALL 
Java_NativeSum_nativeSum (JNIEnv * e, jclass c, jint i, jint j) {
    int k = i + j;
    return k;
}

Compile your NativeSum.c file. Remember to specify the path of the jni.h file to include the library

$ cc -c -I"/System/Library/Frameworks/JavaVM.framework/Headers/" NativeSum.c

Create a shared library for java to access your c implementation

$ cc -dynamiclib -o libnativesum.jnilib NativeSum.o -framework JavaVM

Run your program

$ java NativeSum
30

If you end up with the number 30 in your terminal, you have successfully called your (first) c function from java smiley

Leave a comment

(Required)
(Required)
Captcha