On Jun 26, 2007, at 12:12 PM, <bb...@cox.net> <bb...@cox.net> wrote:
I'm just starting out with JNA. I need to call a .dll. Here's
roughly what the code looks like so far:
// media = (Media) Native.loadLibrary("media",Media.class)
PointerByReference phi = new PointerByReference();
media.createHandle(phi);
Pointer ih = phi.getValue();
media.readImage(ih);
media.frobImage(ih);
...
media.destroyHandle(ih);
I am supposed to destroyHandle(), to reclaim resources. My
instinct (which may be poor, since I'm a little shakey on this) is
to just override Pointer.finalize() in a subclass (call it
ImagePointer) and have ImagePointer.finalize() do
"media.destroyHandle(this);". Aside from the problem of having a
ImagePointer.finalize() know about "media", there is the more
immediate problem that I cannot subclass Pointer(), because the
ctors are private to avoid pointer mayhem.
So, how should I ensure that the code always does destroyHandle(ih)
when it drops an "ih" on the floor? Is there a typical way?
I just get rid of pointers in a finally block, but that doesn't work
well for long-lived pointers. Wayne Meissner has done some stuff
with gstreamer, which uses a number of pointer objects of different
types, although I think the v3 branch he's using allows derived
pointer types. I'm not sure where he's keeping the gstreamer code
he's working on, but I'm sure he'll chime in.
It might make sense to have a protected copy constructor for Pointer,
so that given a Pointer object, you can create your custom type given
the original as an argument. Then you could use the type mapping
system to convert the generic Pointer types to your desired type.
As for your derived type having a reference to its "free" method,
usually the library interface will define the derived type, so
initializing a ref in the ctor, accessing a static ref, or generating
a dynamic ref on the fly is not a big deal.