To make a class called TestClass that uses
a native method called test, follow these steps:
1) Write TestClass.java:
class TestClass {
public
native void test(); //no body
static
{System.loadLibrary("TestClass");}
}
2) Write the function test in TestClassImp.c :
#include <jni.h>
#include "TestClass.h"
#include <stdio.h>
void TestClass_test(struct HTestClass *myhandler)
{
printf("OK!\nIt worked\n");
}
3) Now, create the TestClass.h and TestClass.c
using javah:
javah TestClass, to create
header file
javah -stubs TestClass, to
create the stub file
4) Use javac and gcc to compile and link:
javac TestClass.java
gcc -c -fPIC -I(jdk_path)/include
-I(jdk_path)/include/genunix TestClass.c
gcc -c -fPIC -I(jdk_path)/include
-I(jdk_path)/include/genunix TestClassImp.c
gcc -shared -Wl,-soname,libTestClass.so
-o libtestClass.so TestClass.o TestClassImp.o
5) Set the library path:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.
6) Create the Main.java, just to test:
class Main {
public
static void main(String[] args) {
new TestClass().test();
}
}
7) Compile Main.java and execute Main.class...
These file contains some files whit examples:
voidtest.tgz : the simplest example
returnint.tgz: an example returning an int
intstringint.tgz: an int as parameter,
access a string directly and returns an int
stringparam.tgz:uses a string as parameter