调用c++写的动态库,仅学的一点c++知识,全部还给了老师,ε=(´ο`*)))唉
有时候需要使用,就用到了jna技术。
对于dll中简单的方法,调用起来也简单。但是如果里面有回调函数,就还是第一次接触,在此做一个记录。
例如:
有CustomSDK.dll,
C++中有如下定义
typedef void(__stdcall *CustomSDKInitCallback)(int nCode, const char* msg);
bool __stdcall CustomInitSDK(const char* key, const char* val, CustomSDKInitCallback funcSDKInitCallback);
则在java中调用的步骤如下
1、定义接口继承Library。
当然也可以定义成class类。
public interface Custom extends Library {
Custom instance = Native.loadLibrary("CustomSDK", Custom.class);
public boolean CustomInitSDK(String key, String val, CustomSDKInitCallback funcSDKInitCallback);
}
还有一种加载dll的方法是
System.loadLibrary("CustomSDK");
2、对于c++中的回调函数,CustomSDKInitCallback,在定义一个接口继承Callback
import com.sun.jna.Callback;
public interface CustomSDKInitCallback extends Callback {
void SDKInitCallback(int nCode, String msg);
}
3、在测试类中调用Custom类中的方法,回调函数实现CustomSDKInitCallback接口即可
public static void main(String[] args) {
String strAPIKey = "xxxxxx";
String strAPISecret = "xxxxxx";
Custom.instance.CustomInitSDK(strAPIKey, strAPISecret, new CustomSDKInitCallback() {
@Override
public void SDKInitCallback(int nCode, String msg) {
System.out.println("参数1\tcode:" + nCode + ",参数2:" + msg);
}
});
}
最后,附上JNA的api,http://java-native-access.github.io/jna/4.4.0/javadoc/