隨筆-10  評論-36  文章-6  trackbacks-0
          JAVA可以通過JNI接口訪問本地的動態(tài)連接庫,從而擴(kuò)展JAVA的功能。使用JAVA JNI接口主要包括以下步驟:
          (1)編寫JAVA代碼,注明要訪問的本地動態(tài)連接庫和本地方法;
          (2)編譯JAVA代碼得到.class文件;
          (3)使用javah -jni 生成該類對應(yīng)的C語言.h文件;
          (4)使用C/C++實(shí)現(xiàn)(3)生成的.h文件中聲明的各函數(shù);
          (5)編譯C/C++實(shí)現(xiàn)代碼生成動態(tài)連接庫。
          本文使用一個(gè)簡單的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)生成實(shí)現(xiàn)函數(shù)頭文件

          javah -classpath . helloWorld

          得到的文件內(nèi)容如下:

          /* 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中實(shí)現(xiàn)上述函數(shù)

          #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的關(guān)鍵:通過env我們可以使用JAVA提供的一組函數(shù)操作與轉(zhuǎn)換函數(shù)傳遞的參數(shù)。

          (5)編譯VC項(xiàng)目得到動態(tài)連接庫 examdll.dll。

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


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

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

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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 武宣县| 徐闻县| 辽宁省| 安仁县| 河源市| 郎溪县| 海兴县| 玉溪市| 明水县| 札达县| 河北区| 平度市| 惠州市| 察雅县| 锡林浩特市| 南雄市| 宝清县| 江口县| 华宁县| 湄潭县| 尼玛县| 开江县| 临颍县| 平度市| 宁波市| 灵石县| 手游| 海城市| 天柱县| 讷河市| 蒙自县| 平顶山市| 开化县| 宾川县| 交城县| 万源市| 汉中市| 北辰区| 青阳县| 登封市| 乐山市|