1. 寫Java類,其中定義了native方法
public class WitWrapper { static { System.loadLibrary("witengine"); } /** * @param args */ public static void main(String[] args) { new WitWrapper().run(); } private void run() { solve("C:\\temp\\witlib\\problem.txt"); } public native static int solve(String filename);}
2. 在命令列下用javah產生.h檔案,內容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class XXX_WitWrapper */#ifndef _Included_XXX_witwrapper_WitWrapper#define _Included_XXX_witwrapper_WitWrapper#ifdef __cplusplusextern "C" {#endif/* * Class: XXX_WitWrapper * Method: solve * Signature: (Ljava/lang/String;)I */JNIEXPORT jint JNICALL Java_XXX_WitWrapper_solve (JNIEnv *, jclass, jstring);#ifdef __cplusplus}#endif#endif
3. 複製.h檔案到一個vc++6.0的dll工程裡,用vs2005得到的dll會依賴msvcr80d.dll等其他dll,不建議。把$jdk_dir$/include裡的jni.h和$jdk_dir$/include/win32裡的jni_md.h也添加到這個工程裡。
4. 按.h檔案實現.c檔案對應的方法,如下例,注意jstring類型要轉換成char *類型,否則即使英文也會有亂碼:
/**************************************************************************** * * Sample WIT API Program. * Runs implosion on the Diner problem. * ****************************************************************************/#include <stdlib.h>#include "wit.h"#include "jni.h"/****************************************************************************//* Main Program *//****************************************************************************/JNIEXPORT jint JNICALL Java_XXX_WitWrapper_solve (JNIEnv * env, jclass jc, jstring file){ WitRun * theWitRun; const char *str = (*env)->GetStringUTFChars(env, file, 0);//把jstring轉換為char *,否則會有錯 printf(str); /* Initialize WIT */ witNewRun( &theWitRun ); witInitialize ( theWitRun ); witReadData (theWitRun, str); /************************************************************************* * * Finished entering data * ************************************************************************/ witOptImplode( theWitRun ); witWriteExecSched( theWitRun, "execsched.txt", WitBSV ); witWriteShipSched( theWitRun, "shipsched.txt", WitBSV ); witDeleteRun( theWitRun ); exit (0);} /* main */
5. 編譯產生.dll檔案,把它和其他依賴的檔案放在path環境變數包含的一個目錄下,在java裡就可以調用了。注意調用這個dll的java類名(包括所在包)不能改,否則會出現UnsatisfiedLinkException,如果一定要改名,只能重建一遍dll了。