JNA 调用Dll实例
工作需要,调用别人写的Dll来实现一些功能,去网上找了一些资料,发现都无法实现,会报错,找不到dll或者无法loadDll,调查修改后,实现了一个小demo,记录下来(本人记性不好。。。。)
先来使用VS2010写了一个简单的C++代码:
#include <windows.h>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#define MYLIBAPI extern "C" __declspec( dllexport )
MYLIBAPI int add(int a,int b);
int add(int a,int b){
cout << "Hello, fei! I`m C++!" << endl;
return a + b;
}
C++代码部分注意:
本人是64位windows7机器,生成的debug版本时不好用,用java调用的时候会提示,无法load dll
所以此处要注意生成release版本的64位DLL
java代码部分:
package testDll;
import com.sun.jna.Library;
import com.sun.jna.Native;
public interface testDll extends Library{
testDll HUPF =
(testDll)Native.loadLibrary("hupf.dll",
testDll.class);
public int add(int a , int b);
public int main();
}
package testDll;
public class Main {
public static void main(String[] args) {
System.out.println(testDll.HUPF.add(10, 100));
}
}
这样才能成功调用到DLL,执行结果:
Hello, fei! I`m C++!
110
找度娘看资料发现Java调用dll目前有两种方式,一个是JNI,一个是JNA,都说JNI不好用,我也没有详细去了解,当前例子是用的JNA,本人新手,写的不对,欢迎大家一起来探讨,谢谢

浙公网安备 33010602011771号