隨筆-10  評論-36  文章-6  trackbacks-0
          JAVA可以通過JNI接口訪問本地的動態連接庫,從而擴展JAVA的功能。使用JAVA JNI接口主要包括以下步驟:
          (1)編寫JAVA代碼,注明要訪問的本地動態連接庫和本地方法;
          (2)編譯JAVA代碼得到.class文件;
          (3)使用javah -jni 生成該類對應的C語言.h文件;
          (4)使用C/C++實現(3)生成的.h文件中聲明的各函數;
          (5)編譯C/C++實現代碼生成動態連接庫。
          本文使用一個簡單的helloWorld示例演示JNI的使用。

          (1)編寫JAVA代碼
          public class helloWorld
          {
              public native void SayHello(String name);

              static
              {
                  System.loadLibrary("examdll");
              }

              public static void main(String [] argv)
              {
                  helloWorld hello = new helloWorld();
                  hello.SayHello("myName");
              }
          }

          (2)編譯JAVA代碼

          javac helloWorld.java

          (3)生成實現函數頭文件

          javah -classpath . 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:    SayHello
           * Signature: (Ljava/lang/String;)V
           */
          JNIEXPORT void JNICALL Java_helloWorld_SayHello
            (JNIEnv *, jobject, jstring);


          #ifdef __cplusplus
          }
          #endif
          #endif

          (4)在VC中實現上述函數

          #include "helloWorld.h"
          #include <stdio.h>
          #include <string.h>
          void JNICALL Java_helloWorld_SayHello(JNIEnv * env, jobject obj, jstring str)
          {
              jboolean  b  = true;
              char s[80];
              memset(s, 0, sizeof(s));
              strcpy_s(s ,(char*)env->GetStringUTFChars(str, &b));
              printf("Hello, %s", s);
              env->ReleaseStringUTFChars(str , NULL);
          }

          **** 這是JNI的關鍵:通過env我們可以使用JAVA提供的一組函數操作與轉換函數傳遞的參數。

          (5)編譯VC項目得到動態連接庫 examdll.dll。

          ===================================
          附:如何操作與返回JAVA的參數與類型,這篇文章有些實際的例子可供參考:
          http://blog.sina.com.cn/s/blog_548cc485010005ct.html


          posted on 2008-02-11 13:29 飛鷹 閱讀(30578) 評論(2)  編輯  收藏

          評論:
          # re: JAVA JNI 使用實例 2013-03-01 13:34 | ee
          eeeeee  回復  更多評論
            
          # re: JAVA JNI 使用實例 2013-04-07 09:10 | dads
          類名  回復  更多評論
            

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 泾川县| 莆田市| 贡觉县| 泗阳县| 刚察县| 麦盖提县| 乐山市| 西乌珠穆沁旗| 若尔盖县| 灯塔市| 霍山县| 金华市| 平湖市| 海伦市| 临海市| 公主岭市| 华坪县| 师宗县| 台前县| 怀宁县| 青海省| 镇雄县| 汪清县| 晋州市| 文昌市| 仙居县| 绥阳县| 康平县| 新乡市| 叶城县| 水富县| 太原市| 南华县| 阿勒泰市| 滨州市| 洪雅县| 尼玛县| 大邑县| 竹北市| 甘肃省| 神木县|