java中native方法的使用

來源:互聯網
上載者:User

標籤: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方法的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.