2007年7月3日 星期二

JNI - Java Native Interface

The Java Native Interface (JNI) is a programming framework that allows Java code running in the Java virtual machine (VM) to call and be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages, such as C, C++ and assembly.
... from the link

HelloWorld.java
class HelloWorld
{
public native int[][] multiply(int A[][], int B[][]);
static
{
System.loadLibrary("HelloWorldImp");
}

public static void main(String[] args)
{
HelloWorld test = new HelloWorld();
int[][] A = new int[5][5];
int[][] B = new int[5][5];
int[][] result = test.multiply(A, B);
System.out.println(result[0][0]);
}
}

然後使用 javac HelloWorld.java 產生出 HelloWorld.class
接下來再使用 javah HelloWorld 產生出 HelloWorld.h

HelloWorld.h
/* DO NOT EDIT THIS FILE - it is machine generated */

#ifndef __HelloWorld__
#define __HelloWorld__

#include

#ifdef __cplusplus
extern "C"
{
#endif

JNIEXPORT jobjectArray JNICALL Java_HelloWorld_multiply (JNIEnv *env, jobject, jobjectArray, jobjectArray);

#ifdef __cplusplus
}
#endif

#endif /* __HelloWorld__ */

再把 HelloWorld.c 寫出來
HelloWorld.c
#include "HelloWorld.h"

JNIEXPORT jobjectArray JNICALL Java_HelloWorld_multiply (JNIEnv *env, jobject obj, jobjectArray A, jobjectArray B);
{
jobjectArray C;
...
return C;
}

最後使用 gcc -Wall -g -shared -fPIC HelloWorld.c -o libHelloWorldImp.so
現在終於可以執行 Java 程式了
java -Djava.library.path=./ HelloWorld
使用 Java 來做跨平台程式開發
在關鍵部份再利用 JNI 來將平台特性最佳化
張貼留言