Using Java objects from C++
Dave Menendez
dave@sycamorehq.com
Mon May 3 18:47:00 GMT 2004
I'm a newbie to GCJ and am using GCC 3.4. I have a Java library that I
needed to use from C/C++ and was quite happy at how easy it was to
instantiate and use Java objects from C++.
I do have one nagging problem, though, and although I've searched this
mailing list several ways, I can't seem to find a definitive answer to
this question: can I instantiate a Java object from (pure) C++ and
somehow indicate to the JVM that I have retained a reference to it
(i.e., I want to store a pointer to the Java object in a C struct or as
a C++ instance member, but I don't want the GC to get rid of the object
until I say I'm done with it)?
I've seen some suggestions that say to allow the garbage collector to
manage your C++ object or explicitly allocating/deallocating the C++
objects in the GC heap, but I didn't find anything in the CNI headers
that would seem to provide this functionality, so an example would help.
>From other threads, it seems the basic problem is that the JVM doesn't
know anything about your C/C++ code holding pointers to Java objects.
Would allocating a C++ struct via JvMalloc (from gcj/cni.h) and simply
storing the Java object pointer in this struct alleviate this problem?
If not, is there (or could there be) a Glib-like set of methods, ref()
and unref(), that could be added to GCJ's java::lang::Object
specifically for C++ code to indicate to the JVM that it is holding one
or more references to the Java object?
A co-worker suggested perhaps creating a very simple Java object that
simply stores references to other Java objects, and instantiating one
static, global instance of this object in C++. That would mean if I
wanted to keep a Java object around in C++, I'd just have to add it to
this static Java object, and then remove it when I'm done with it. It's
kludgy, but might it work?
Any insight into this problem would be much appreciated - I can't be the
first one that wants to do this. Thanks to GCJ, I've passed the hurdle
of porting a sizable Java library into C++; the only hurdle remaining
for me is how to fully integrate Java objects created by this library
into my C/C++ library by being able to instantiate and keep Java objects
around in C/C++ world.
Thanks,
Dave
P.S. One more thing, I was a bit mystified when I read in the mailing
list that even though I use "new" to allocate a Java object from C++,
I'm not supposed to call "delete" to get rid of it, but that it somehow
automagically gets collected by the GC. If someone could provide a
brief description of how the GC decides what is eligible for collection
or point me to a document to help me understand the logic, that would
also be much appreciated.
More information about the Java
mailing list