標籤:java native方法 dll檔案
在很多情況下,java需要調用其他語言的代碼,比如c的代碼,那麼這個時候java中native方法就發揮作用了,下面就介紹native方法的使用。
一、JNI使用流程
a.編寫帶有native聲明的方法的Java類
b.使用javac命令編譯編寫的Java類
c.使用java -jni ****來產生尾碼名為.h的標頭檔
d.使用其他語言(C、C++)實現本地方法
e.將本地方法編寫的檔案產生動態連結程式庫
二、實踐
1、編寫類代碼
package com.sunny.demo;public class Demo01 { public native void hello();//沒有實現 static{ System.loadLibrary("hello");//在類載入的 時候載入dll } public static void main(String[] args){ new Demo01().hello(); }}
2、編譯
javac com/sunny/demo/Demo01.java(注意,我這裡是帶包編譯)
3、產生.h檔案
javah -jni com.sunny.demo.Demo01(注意,標頭檔組建目錄的位置,不知.java檔案的位置,而在和包同級目錄中,這裡產生的檔案名稱為com_sunny_demo_Demo01.h)
4、用c實現hello方法(vc++6.0建立dll工程)
(1)其中com_sunny_demo_Demo01.h中代碼如下(javah自動產生的)
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_sunny_demo_Demo01 */#ifndef _Included_com_sunny_demo_Demo01#define _Included_com_sunny_demo_Demo01#ifdef __cplusplusextern "C" {#endif/* * Class: com_sunny_demo_Demo01 * Method: hello * Signature: ()V */JNIEXPORT void JNICALL Java_com_sunny_demo_Demo01_hello (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif
(2).c檔案,實現hello方法
#include<stdio.h>#include"hello.h"JNIEXPORT void JNICALL Java_com_sunny_demo_Demo01_hello(JNIEnv * a, jobject b){printf("hello world");}
(3)用VC++6.0編譯一下在debug目錄中就產生好了dll檔案。
說明:編譯時間如果產生如下錯誤:fatal error C1083: Cannot open include file: ‘jni.h‘: No such file or directory。說明沒有找到jni.h,到jdk的安裝目錄 include/jni.h;win32/jni_md.h;win32/jawt_md.h這3個檔案拷貝到vc的安裝目錄include中
5.將dll放到產生.h的那一集目錄中,運行java com.sunny.demo.Demo01就會出現如下結果
三、總結:
上面的例子中,我是帶包編譯的,所以檔案存放和產生的位置一定要注意,在java層面我們只需要dll檔案,.h和.cd 檔案的目的只是為了產生dll檔案.最後給出我代碼的目錄結果
.h檔案是javah產生的,dll檔案是應該放的位置(如果不放在這個位置,運行報錯,找不到hello這個庫)
dll參考文章:http://www.cnblogs.com/chio/archive/2007/11/03/948480.html
external c :http://www.cnblogs.com/rollenholt/archive/2012/03/20/2409046.html
java native文章: http://blog.163.com/[email protected]/blog/static/21475796200701491621267
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java中native方法的使用