简体   繁体   English

如何使用JNA回调

[英]How to use JNA callback

I am using JNA to call functions of a dll file. 我正在使用JNA来调用dll文件的函数。

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;
}  
}

My Java Interface looks like this: 我的Java接口如下所示:

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);
}

And finally the java main: 最后java主:

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;
        }
    });
}

My problem is that I got the error, that java cannot find the function setCallback. 我的问题是我得到了错误,java无法找到函数setCallback。 What's wrong on my code? 我的代码出了什么问题?

Thank you for your help! 谢谢您的帮助!

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". C ++与C不同。转储DLL中的符号(http://dependencywalker.com),您将看到函数名称(至少从链接器的角度来看)不是“setCallback”。

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. 使用extern "C"可以避免在导出的函数上进行名称修改,重命名Java函数以匹配导出的链接器符号,或使用FunctionMapper将Java方法名称映射到链接器符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM