Java JNI 執行個體

來源:互聯網
上載者:User

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

聯繫我們

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