Java调用动态库所需要关心的问题
Type
Length
JNative class
DWORD
4
org.xvolks.jnative.misc.basicStructures.LONG
HWND
4
org.xvolks.jnative.misc.basicStructures.HWND
COLORREF
4
org.xvolks.jnative.misc.basicStructures.LONG
COLORREF*
4
org.xvolks.jnative.pointers.Pointer
LPARAM
4
org.xvolks.jnative.misc.basicStructures.LPARAM
LPCCHOOKPROC
4
org.xvolks.jnative.util.Callback
LPCTSTR
4
org.xvolks.jnative.pointers.Pointer
?
?
?
?
?
?
?
?
方法
Class
作用
一般用到的方法(参数略,参考Doc)
org.xvolks.jnative.Jnative
装载dll文件,定位函数
JNative(),setParameter(),setRetVal(),getRetVal() etc.
org.xvolks.jnative.pointers.Pointer
替代本地函数中的的指针,需要先申请一块内存空间,才能创建
Pointer(),dispose()
org.xvolks.jnative.pointers.memory.MemoryBlockFactory
申请一块内存空间
createMemoryBlock()
org.xvolks.jnative.exceptions.NativeException
抛出装载,定位等方面的异常
?
org.xvolks.jnative.Type
列举和管理Jnative需要的不同的数据类型
?
简单测试,Javadoc 下和官方网上有些例子,下面的是我随便从IC读卡程序中找了个DLL进行的测试:
SCReader.dll 下的SCHelp_HexStringToBytes()函数原型
SCREADER_API WINAPI long SCHelp_HexStringToBytes(
LPCTSTR pSrc,
BYTE* pTar,
int MaxCount
);
注意:dll文件需要放到System32下,否则可能找不到
通过Jnative 用java 来调用代码如下
package onlyfun.dllcall;
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.exceptions.NativeException;
import org.xvolks.jnative.pointers.Pointer;
import org.xvolks.jnative.pointers.memory.MemoryBlockFactory;
import org.xvolks.jnative.Type;
public class UserCall {
??? /**
??? * return 转换成功的字节数
??? */
??? static JNative Something = null;
??? static Pointer pointer;
??? public String getSomething(String pSrc, Pointer pTar, int MaxCount) throws NativeException, IllegalAccessException{
?????
?????? try{
?????????? if(Something == null){
????????????? pTar = new Pointer(MemoryBlockFactory.createMemoryBlock(36));
????????????? Something = new JNative("SCReader.DLL", "SCHelp_HexStringToBytes");
// 利用org.xvolks.jnative.JNative 来装载 SCReader.dll,并利用其SCHelp_HexStringToBytes方法
????????????? Something.setRetVal(Type.INT);
// 指定返回参数的类型
?????????? }
?????????? int i="0";
?????????? Something.setParameter(i++,pSrc);
?????????? Something.setParameter(i++,pTar);
?????????? Something.setParameter(i++,MaxCount);
??? ?????? System.out.println("调用的DLL文件名为:"+Something.getDLLName());
?????????? System.out.println("调用的方法名为:"+Something.getFunctionName());
//传值
??? ??? ?? Something.invoke();//调用方法
?????????? return Something.getRetVal();
?????? }finally{
?????????? if(Something!=null){
????????????? Something.dispose();//释放
?????????? }
?????? }
??? }
??? public Pointer creatPointer() throws NativeException{
?????? pointer = new Pointer(MemoryBlockFactory.createMemoryBlock(36));
?????? pointer.setIntAt(0, 36);
?????? return pointer;
??? }
??? public static void main(String[] args) throws NativeException, IllegalAccessException {
??? ?? UserCall uc = new UserCall();
?????? String result = uc.getSomething("0FFFFF", uc.creatPointer(), 100);
?????? System.err.println("转换成功的字节数为:"+result);
?????? TestCallback.runIt();
??? }
}