大約四、五年前吧~ 我記得當時為了將以前用VB寫的定時關機程式要移植到Java版時~ 遇到了一個需要呼叫Windows API的問題~ 這時候透過JNI(Java Native Interface)就不失為一種解決方式~ 當然這樣的方式也就等同於向跨平臺的優勢說bye bye嚕~ 底下是以前所記錄的一些流程步驟(以HelloWorld為範例):
寫一個 HelloWorld.java
class HelloWorld
{
public native void helloworld();
static {
System.loadLibrary("jni");
}
public static void main(String[] args)
{
new HelloWorld().helloworld();
}
}
編譯 HelloWorld.java
javac HelloWorld.java
產生 header file
javah -jni HelloWorld
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: helloworld
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_helloworld
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
寫一個 jni.c
#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>
JNIEXPORT void JNICALL
Java_HelloWorld_helloworld(JNIEnv *env, jobject obj)
{
printf("Hello world!\n");
return;
}
編譯成DLL for Windows
gcc -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -I "C:\Program Files\Java\jdk1.6.0\include" -I "C:\Program Files\Java\jdk1.6.0\include\win32" -shared -o jni.dll jni.c
編譯成SO for Linux
gcc -fPIC -Wall -I/usr/lib/jvm/java-6-sun/include/ -I/usr/lib/jvm/java-6-sun/include/linux -shared -o libjni.so jni.c
呼叫HelloWorld
java HelloWorld
成功!^^
Hello world!

請問在"編譯成DLL"這部分使用到的gcc指令需要安裝什麼軟體程式嗎?
我在命令列輸入這一串指令後,系統回應'gcc'不是內部或外部命令、可執行的程式或批次檔。
2011-09-15 17:27:44
請參考MinGW: http://www.mingw.org/wiki/InstallationHOWTOforMinGW
2011-09-15 23:54:51
請問一下
執行:javah -jni HelloWorld
結果:
error: cannot access HelloWorld
class file for HelloWorld not found
javadoc: error - Class HelloWorld not found.
Error: No classes were specified on the command line. Try -help.
已經產生class檔了,到底是哪裡出了問題呢?
2011-11-13 14:25:20