如何使用JNA回调 [英] How to use JNA callback
问题描述
我使用JNA来调用dll文件的函数。
I am using JNA to call functions of a dll file.
simpleDLL.h:
simpleDLL.h:
typedef int (__stdcall *eventCallback)(unsigned int id, int value);
namespace test
{
class hotas
{
public:
static __declspec(dllexport) int readValue(int a);
static __declspec(dllexport) void setCallback(eventCallback evnHnd);
};
}
simpleDLL.cpp:
simpleDLL.cpp:
#include "simpleDLL.h"
#include <stdexcept>
using namespace std;
namespace test
{
eventCallback callback1 = NULL;
int test::readValue(int a)
{
return 2*a;
}
void test::setCallback(eventCallback evnHnd)
{
callback1 = evnHnd;
}
}
我的Java接口看起来像这样:
My Java Interface looks like this:
public interface DLLMapping extends Library{
DLLMapping INSTANCE = (DLLMapping) Native.loadLibrary("simpleDLL", DLLMapping.class);
int readValue(int a);
public interface eventCallback extends Callback {
boolean callback(int id, int value);
}
public void setCallback(eventCallback evnHnd);
}
最后是java main:
And finally the java main:
public static void main(String[] args) {
DLLMapping sdll = DLLMapping.INSTANCE;
int a = 3;
int result = sdll.readValue(a);
System.out.println("Result: " + result);
sdll.setCallback(new eventCallback(){
public boolean callback(int id, int value) {
//System.out.println("bla");
return true;
}
});
}
我的问题是我得到错误,java找不到函数setCallback 。
我的代码有什么问题?
My problem is that I got the error, that java cannot find the function setCallback. What's wrong on my code?
感谢您的帮助!
推荐答案
C ++与C不一样。从DLL中删除符号(http://dependencywalker.com),你会看到函数名(至少从链接器的角度来看)是不要setCallback。
C++ is not the same thing as C. Dump the symbols from your DLL (http://dependencywalker.com), and you will see that the function name (at least from the linker's point of view) is not "setCallback".
使用 externC
可避免导出的函数出现名称错误,以匹配导出的链接器符号,或使用FunctionMapper将Java方法名称映射到链接器符号。
Use extern "C"
to avoid name mangling on exported functions, rename your Java function to match the exported linker symbol, or use a FunctionMapper to map the Java method name to the linker symbol.
这篇关于如何使用JNA回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!