Lowell
Lowell

Reputation: 21

Create JNA mapping for C struct with function pointer

I am creating JNA mappings to the OpenMAX C library. Along the way I am also learning C. I have encountered a struct that I am unsure how to map to, and that I have been unable to find any resources to help.

Here is a snippet from the struct

typedef struct OMX_COMPONENTTYPE {    

    OMX_VERSIONTYPE nVersion;

    OMX_ERRORTYPE (*SetParameter)(
                 OMX_HANDLETYPE hComponent, 
                 OMX_INDEXTYPE nIndex,
                 OMX_PTR pComponentParameterStructure);
...

"nVersion" is a normal member and is easily mappable in java.

My problem is with the functional pointer SetParameter. (I think that's what it is)

In Java, structs get mapped to a child of the jna.Structure class. Because this is a class (not an interface), I cannot define a method header without a body which is how I have otherwise mapped methods.

Does anyone know what this mapping is supposed to look like?

Thanks

Upvotes: 0

Views: 1025

Answers (1)

technomage
technomage

Reputation: 10069

JNA uses Callback objects to represent function pointers, and includes a description of callback usage.

Make an interface that derives from Callback, which implements a single method that matches your function pointer's.

public class MyStructure extends Structure {    

    public MyCallback callback;

    public interface MyCallback extends Callback {
        void invoke();
    }
}

If you read the struct from native memory, you'll get a proxy object you can use to call the function pointer.

From Java code, you can then assign the field a new value like thus:

MyStructure s = ...;
s.callback = new MyCallback() {
    public void invoke() {
        // your callback implementation here
    }
};

Upvotes: 1

Related Questions