开发者

JNI wrapper or alternative for callbacks

I need to call from Java a native library , which requires callback registration (and using callbacks then).

Is there any wrapper over JNI or JNI alternative for such situation? It seems that JNA, HawtJNI and others does not support callbacks to Java开发者_开发知识库 ...

Thank you!


Look for JNA(Java Native Access), It's much more convenient way than JNI.


Let say we have a method in our C library which will notify the application if a record has been deleted by another process. It provides us with a method to add a callback,

int register_delete_monitor( void* fn);

and the callback expected takes a parameter of a record.

In our Java library, we would create a Callback for this method:

interface DeletedRecordCallback extends Callback { void callback (Record r); } ... // and in our Library Interface: int register_delete_monitor (DeletedRecordCallback drc);

Now we can pass in an implementation of our DeletedRecordCallback and have it registered as a callback in the C library.

There are one caveat with the use of callbacks in JNA. The callback must not be garbage collected unless it's been unregistered. This is especially true for long lived callbacks. A call to a garbage-collected callback will crash the vm. This can be simply avoided by hanging on to the instance of the callback - a singleton will work quite well in this context. Otherwise, it is important to have the callback instance deregister itself in it's finalize method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜