1.安装
到jnative.sourceforge.net下载最新的JNative二进制包,解压后得到3个文件:JNativeCpp.dll,libJNativeCpp.so,JNative.jar,其中:
JNativeCpp.dll 放在windows/system32目录下
libJNativeCpp.so linux下使用
JNative.jar 导入工程中
2.使用
2.1.加载dll文件
JNative可使用两种方式加载dll文件:
使用System.loadLibrary加载
使用此方法可加载系统目录中的dll文件。可以先把dll文件复制到system32目录下,使用文件前缀名作为参数来加载dll文件。
使用System.load加载
此方法参数为dll文件全路径名。
2.2.调用函数
1、首先创建JNative对象:
JNative jnative = new JNative(dll文件名, 函数名);
2、设置返回值类型:
jnative.setRetVal(Type.INT);
3、设置参数
jnative.setParameter(0, Type.STRING, …); //设置第一个参数为字符串
jnative.setParameter(1, Type.INT, String.valueof(…)); //设置第二个参数为整数
4、执行
n.invoke();
5
、获取返回值
Integer.parseInt(jnative.getRetVal());
2.3. 一个实例
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.exceptions.NativeException;
import org.xvolks.jnative.misc.basicStructures.AbstractBasicData;
import org.xvolks.jnative.pointers.Pointer;
import org.xvolks.jnative.pointers.memory.MemoryBlockFactory;
/**
* SystemTime
*
* typedef struct _SYSTEMTIME {
* WORD wYear;
* WORD wMonth;
* WORD wDayOfWeek;
* WORD wDay;
* WORD wHour;
* WORD wMinute;
* WORD wSecond;
* WORD wMilliseconds;
* } SYSTEMTIME,
*/
public class SystemTime extends AbstractBasicData<systemtime> {
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
/**
* 分配内存,并返回指针
*/
public Pointer createPointer() throws NativeException {
pointer = new Pointer(MemoryBlockFactory.createMemoryBlock(getSizeOf()));
return pointer;
}
/**
* 内存大小
*/
public int getSizeOf() {
return 8 * 2;
}
/**
* 获取通过内存指针解析出结果
*/
public SystemTime getValueFromPointer() throws NativeException {
wYear = getNextShort();
wMonth = getNextShort();
wDayOfWeek = getNextShort();
wDay = getNextShort();
wHour = getNextShort();
wMinute = getNextShort();
wSecond = getNextShort();
wMilliseconds = getNextShort();
return this;
}
public SystemTime() throws NativeException {
super(null);
createPointer();
}
public String toString() {
return wYear + "/" + wMonth + "/" + wDay + " at + " + wHour + ":" + wMinute + ":" + wSecond
+ ":" + wMilliseconds;
}
public static SystemTime GetSystemTime() throws NativeException, IllegalAccessException {
// 创建对象
JNative nGetSystemTime = new JNative("Kernel32.dll", "GetSystemTime");
SystemTime systemTime = new SystemTime();
// 设置参数
nGetSystemTime.setParameter(0, systemTime.getPointer());
nGetSystemTime.invoke();
// 解析结构指针内容
return systemTime.getValueFromPointer();
}
public static void main(String[] args) throws NativeException, IllegalAccessException {
System.err.println(GetSystemTime());
}
}</systemtime>