How to use JNA callback

我只是一个虾纸丫 提交于 2019-12-20 03:49:12

问题


I am using JNA to call functions of a dll file.

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:

#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:

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:

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. What's wrong on my code?

Thank you for your help!


回答1:


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".

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.



来源:https://stackoverflow.com/questions/11849595/how-to-use-jna-callback

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!