新建动态库的代码:
#include "stdafx.h"
#define EXPORT extern "C" __declspec(dllexport)
EXPORT int plus(int a, int b);
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
int plus(int a, int b){
return (a + b) * (a - b);
}
然后再在java工程下添加jna.jar文件;
执行相对应的java文件:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class HelloWorld {
//编写一个接口,必须继承Library,他要在加载库文件时用
public interface CLibrary extends Library {
//加载库文件,Platform.isWindows()可以判断系统类型
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("zhangwei2" ,CLibrary.class);
//定义方法,与c语言标准的一致
int plus(int a,int b);
}
public static void main(String[] args) {
int aa = 0;
for (int i = 0; i < 5; i++) {
aa = CLibrary.INSTANCE.plus(i, 4);
System.out.println("------------------------");
System.out.println("" + i +" + 4 = " + aa);
}
}
}