Turn a Callback into a Pointer in JNA

时光总嘲笑我的痴心妄想 提交于 2019-12-08 08:03:35

问题


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

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