reza
reza

Reputation: 63

Pointer to a function in java

I have a dynamic link library (DLL) written in c++. In my DLL I have a function like this:

void set_event_callback(EVENT_CALLBACK callback_fcn);

where EVENT_CALLBACK is a function pointer like this:

void (*EVENT_CALLBACK)(int event_type, byte param1, int param2);

I use my DLL in other languages. For example, in C# I call set_event_callback like this:

public delegate void EVENT_CALLBACK(int event_type, byte param1, int param2);
EVENT_CALLBACK HandleEventsDelegate = null;
HandleEventsDelegate = new EVENT_CALLBACK(HandleEvents);
set_event_callback(HandleEventsDelegate);

where HandleEvents is a function like this:

protected void HandleANPREvents(int event_type, byte param1, int param2){ ... }

Now, I want to use my DLL in Java. I'm using JNA to call native code in my java project. I couldn't find function pointers in Java.

How can I call set_event_callback in Java and pass a function to my DLL?

Upvotes: 2

Views: 646

Answers (1)

Daniel Widdis
Daniel Widdis

Reputation: 9131

As the comment by @Mark-Rotteveel states, you should define a functional interface with a single method matching the callback. It could look something like this:

// Extend StdCallLibrary if library is __stdcall
public interface YourDLL extends Library {
    YourDLL INSTANCE = // insert library loading code here

    // Define the callback
    // Extend StdCallCallback if library is __stdcall
    interface HandleANPREvents extends Callback {
        // the function name doesn't matter
        void invoke(int event_type, byte param1, int param2);
    }

    // Define the function using the callback
    void set_event_callback(HandleANPREvents callback_fcn);
}

You can then refer to set_event_callback() in your code.

public static void main(String[] args) {
    HandleANPREvents fn = new HandleANPREvents() {
        @Override
        void invoke(int event_type, byte param1, int param2) {
            // implementation here
        }
    };
    YourDLL.INSTANCE.set_event_callback(fn);
}

Upvotes: 3

Related Questions