使用JNI的步驟

來源:互聯網
上載者:User

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了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.