This is a basic example for using JNI. the project calls four functions written in C from a java class.
Compile java classes.
javac JavaCWrapper.java
javac Main.java
javah -jni command is included in jdk. And will create automatically a C header to import and start writing what we need in C code.
javah -jni JavaCWrapper
Output
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JavaCWrapper */
#ifndef _Included_JavaCWrapper
#define _Included_JavaCWrapper
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JavaCWrapper
* Method: additionFromC
* Signature: (DD)D
*/
JNIEXPORT jdouble JNICALL Java_JavaCWrapper_additionFromC
(JNIEnv *, jobject, jdouble, jdouble);
...
...
...
#include <jni.h>
#include <stdio.h>
#include "JavaCWrapper.h"
/*
* Class: JavaCWrapper
* Method: additionFromC
* Signature: (II)D
*/
JNIEXPORT jdouble JNICALL Java_JavaCWrapper_additionFromC
(JNIEnv *env, jobject o, jdouble a, jdouble b){
return a + b;
}
...
...
...
There are different variants form compiling, as JNI libraries are allocated differently depending on the used OS
The dynamic libraries have .dylib so be sure to use this extension. It can be seen that in JavaCWrapper the imported library is just nvch please avoid problems and call the library as follows: **lib.dylib
gcc -I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers -o libnvch.dylib -shared JavaCWrapper.c
The part after -I could change as it only points where jni.h is allocated.
For windows extension are .dll also don't forget to remove the lib part from the file name.
Same as in MAC.
Once you successfully run the above command, you will see a libctest.so file in the current directory (or libctest.dylib or libctest.dll).
java Main
Missing libraries, are linked dynamically.