JAVA可以通過(guò)JNI接口訪問(wèn)本地的動(dòng)態(tài)連接庫(kù),從而擴(kuò)展JAVA的功能。使用JAVA JNI接口主要包括以下步驟:
(1)編寫(xiě)JAVA代碼,注明要訪問(wèn)的本地動(dòng)態(tài)連接庫(kù)和本地方法;
(2)編譯JAVA代碼得到.class文件;
(3)使用javah -jni 生成該類(lèi)對(duì)應(yīng)的C語(yǔ)言.h文件;
(4)使用C/C++實(shí)現(xiàn)(3)生成的.h文件中聲明的各函數(shù);
(5)編譯C/C++實(shí)現(xiàn)代碼生成動(dòng)態(tài)連接庫(kù)。
本文使用一個(gè)簡(jiǎn)單的helloWorld示例演示JNI的使用。
(1)編寫(xiě)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)鍵:通過(guò)env我們可以使用JAVA提供的一組函數(shù)操作與轉(zhuǎn)換函數(shù)傳遞的參數(shù)。
(5)編譯VC項(xiàng)目得到動(dòng)態(tài)連接庫(kù) examdll.dll。
===================================
附:如何操作與返回JAVA的參數(shù)與類(lèi)型,這篇文章有些實(shí)際的例子可供參考:
http://blog.sina.com.cn/s/blog_548cc485010005ct.html