user1582343
user1582343

Reputation: 15

How to use JNA callback

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!

Upvotes: 1

Views: 8970

Answers (1)

technomage
technomage

Reputation: 10069

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.

Upvotes: 5

Related Questions