问题
I must be missing something. Given an instance of a class that implements com.sun.jna.Callback
, how do I get a function pointer address as a Pointer
, so that I can pass it to a function that takes a void*
parameter (I’m using Pointer
).
Specifically, I want to create a CFNumber
(aka NSNumber*
) using CFNumberCreate(Pointer, int, Pointer) with the address of the function, so that I can call SetSpeechProperty to register a SpeechDoneProcPtr.
回答1:
You don't. You pass the callback instance and let JNA handle the pointer conversions. Make sure you keep a strong reference to the callback object so it doesn't get GC'd.
If you need to, make another function mapping that uses your callback type instead of Pointer
.
You can get the native pointer value for a callback instance, but there are very few reasons why you'd ever need to.
回答2:
I still needed to convert a Callback to Pointer and I found a dirty hack to do it. Call memcpy() with the Callback with zero length copy. memcpy() returns the Callback as a Pointer.
For Windows I define the library where memcpy() is found:
public interface msvcrt extends StdCallLibrary {
Pointer memcpy(Callback dst, Callback src, int size);
}
And then to use it like this:
public Pointer callbackToPointer(Callback callback) {
msvcrt crt = (msvcrt)Native.loadLibrary("msvcrt", msvcrt.class);
return crt.memcpy(callback, callback, 0); //zero length copy returns dest
}
Tada!
来源:https://stackoverflow.com/questions/17282785/turn-a-callback-into-a-pointer-in-jna