JNI, callbacks and remembering the global reference

B

Bill Medland

Is there an easier way to do this?

I am writing a library layer of code that uses JNI to call down into a
library implemented in C.

The C library includes a callback mechanism including both register and
unregister;
e.g. registerCallback(functiontype func, void *context);
unregisterCallback(functiontype func, void *context);

The java library layer will export a similar ability to add and remove a
listener.

The JNI layer will pass the listener as the context and the address of a
small redirector function as the func arguments.

So clearly I will have to call NewGlobalRef on the jobject passed down as
the listener.
(Presumably that global reference will be valid in different environments
when it comes back to the redirector)

The problem is with removing the listener; how am I going to figure out what
jobject to pass to the DeleteGlobalRef.

It seems to me that the JNI layer is going to have to keep a copy of all the
global references generated and then search that list using IsSameObject to
find the global reference that was used that refers to the same object as
the local reference being passed down.

Is there an easier way? Like is there a way to find the global reference
corresponding to a local reference?
 
G

Gordon Beaton

It seems to me that the JNI layer is going to have to keep a copy of
all the global references generated and then search that list using
IsSameObject to find the global reference that was used that refers
to the same object as the local reference being passed down.

Is there an easier way? Like is there a way to find the global
reference corresponding to a local reference?

Nothing forces you to use the reference itself as a key. After
registering the listener, return a value that the caller can use to
deregister it later.

A suitable value might an index into an array where you keep the
listener references. Or you could pass the actual address of a C
struct (cast to long) that holds the reference itself and other
information about the listener you might be storing.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top