JNI這個東西比較複雜 因為前幾天自己剛好做過這個麼東西 所以才推薦你用JNative的哦(我也是剛接觸這個是個菜鳥).....
看樓主這麼執著那我就寫個小例子 大家不要見笑(- -!)
假設現在有個A.dll裡面有個方法叫做int add(int a, int b)現在就是要用jni去調用它
這裡附上A.dll裡面的代碼(自己瞎個的吧 能用就行)
-
C/C++ code
-
#include "stdafx.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
extern"C"int _declspec(dllexport) add(int a ,int b)
{
return a+b;
}
接下來我們的思路自己寫個B.dll然後在這個dll裡面去調用A.dll裡面的這個add方法,然後通過JAVA去調用自己的這個B.DLL....
第一步: 隨便建個txt檔案 呵呵 當然尾碼改上.JAVA寫上
-
Java code
-
publicclass DemoJni{
publicnativeint getNumber(int a,int b);
publicstaticvoid main(String[] args) {
}
}
然後javac一下 沒錯的話 javah 產生了DemoJni.h(如下)
-
C/C++ code
-
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>/* Header for class DemoJni */
#ifndef _Included_DemoJni
#define _Included_DemoJni
#ifdef __cplusplus
extern"C" {
#endif/*
* Class: DemoJni
* Method: getNumber
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_DemoJni_getNumber
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif#endif
用VC++6.0寫B.DLL
建立DLL工程名字為B 在Header FILES->添加這個DemoJni.h
然後就寫B.cpp
-
C/C++ code
-
// B.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "jni.h"
#include "DemoJni.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
JNIEXPORT jint JNICALL Java_DemoJni_getNumber
(JNIEnv * env, jobject o, jint x, jint y)
{
typedef int (*ADD)(int ,int);//函數指標類型 HINSTANCE Hint = ::LoadLibrary("A.dll");//載入我們剛才產生的dll ADD add = (ADD)GetProcAddress(Hint,"add");//取得dll匯出的add方法return add(x,y);
FreeLibrary(Hint);
}
對了在VC++6.0要引入java的一些包 因為我們上面引入了#include "jni.h"
具體做法 工具->選項->目錄->建立兩個路徑 :比如C:\PROGRAM FILES\JAVA\JDK1.5.0_14\INCLUDE
和C:\PROGRAM FILES\JAVA\JDK1.5.0_14\INCLUDE\WIN32
搞定後就可以編譯了 然後在debug檔案下面就產生了我們要的B.DLL
然後A.DLL和B.DLL以及.java檔案放一起咯
下面就是調用 改寫我們的.java檔案如下
-
Java code
-
publicclass DemoJni{
publicnativeint getNumber(int a,int b);
publicstaticvoid main(String[] args) {
System.loadLibrary("B");
DemoJni p=new DemoJni();
System.out.println(p.getNumber(1, 100));
}
}
然後java 一下 然後輸出
101
然後OK!
這個東西如果用JNative來做的話 實在是太簡單了- -!附上JNative的代碼
-
Java code
-
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.exceptions.NativeException;
publicclass test {
static JNative myjnative =null;
publicint getnumber(int a, int b) throws NativeException,
IllegalAccessException {
try {
if (myjnative ==null) {
myjnative =new JNative("A.dll", "add");
myjnative.setRetVal(Type.INT);
}
int i =0;
myjnative.setParameter(i++, a);
myjnative.setParameter(i++, b);
myjnative.invoke();
return myjnative.getRetValAsInt();
} finally {
if (myjnative !=null) {
myjnative.dispose();
}
}
}
publicstaticvoid main(String[] args) throws NativeException,
IllegalAccessException {
test uc =new test();
int result = uc.getnumber(1,100);
System.err.println("result:"+ result);
}
}
Jnative我覺得有個很好的地方就是有POINTER 指標這個東西.....