1.下載JNative的包
JNative-1.3.2下有三個文件:JNativeCpp.dll,libJNativeCpp.so,JNative.jar。
JNativeCpp.dll拷到windows/system32目錄下
libJNativeCpp.so爲Linux中使用的文件
JNative.jar擴展包拷到%JAVA_HOME%/jre/lib/ext下或者導入到工程中
2.Jnative中使用到的一些類和方法
org
.xvolks
.jnative
.Jnative
: 裝載dll文件,定位函數 如:Jnative native=new Jnative("dllName");
JNative
(),setParameter(),setRetVal(),getRetVal()
etc.
org
.xvolks
.jnative
.pointers
.Pointer: 替代本地函數中的的指針,需要先申請一塊內存空間,才能創建,一般使用MemoryBlockFactory
利用工廠模式進行創建.
Pointer(),dispose()
org
.xvolks
.jnative
.pointers
.memory
.MemoryBlockFactory : 申請一塊內存空間
createMemoryBlock()
org
.xvolks
.jnative
.exceptions.NativeException
: 拋出裝載,定位等方面的異常
org
.xvolks
.jnative
.Type
: 列舉和管理Jnative
需要的不同的數據類,一般需要傳值的時候指定所傳值的類型和函數的返回值
3.使用方法
3.1. 加載dll文件
3.2. 調用函數
4.一個簡單的例子:
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.exceptions.NativeException;
public class JNativeTest {
public static final int messageBox(int parentHandle, String
message,
String caption, int buttons) throws NativeException,
IllegalAccessException {
JNative n = null;
try {
n = new JNative("User32.dll", "MessageBoxA"); //
常量DLL_NAME的值爲User32.dll
// 構造JNative時完成裝載User32.dll,並且定位MessageBoxA方法
n.setRetVal(Type.INT); // 指定返回參數的類型
int i = 0;
n.setParameter(i++, Type.INT, "" + parentHandle);
n.setParameter(i++, Type.STRING, message);
n.setParameter(i++, Type.STRING, caption);
n.setParameter(i++, Type.INT, "" + buttons); //
指定位置上的參數類型和值
n.invoke(); // 調用方法
return Integer.parseInt(n.getRetVal());
} finally {
if (n != null)
n.dispose(); // 記得釋放
}
}
public static void main(String[] args) throws NativeException,
IllegalAccessException{
JNativeTest.messageBox(100,"Hello jnative", "jnativetest",
1);
}
}