Using Java objects from C++
Bryce McKinlay
mckinlay@redhat.com
Mon May 3 19:03:00 GMT 2004
Dave Menendez wrote:
>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)?
>>
A very good question. Currently we are lacking an API to register a
reference from CNI. I think we need one. How about something like the
following?
JvNewGlobalRef(jobject)
JvDeleteGlobalRef(jobject)
I'll go ahead and implement something like this if others agree its a
good idea.
>>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.
>>
Right.
>Would allocating a C++ struct via JvMalloc (from gcj/cni.h) and simply
>storing the Java object pointer in this struct alleviate this problem?
>
No, because JvMalloc is actually just a wrapper around malloc. Our GC
doesn't scan the malloc() heap, only its own heap.
>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?
>>
This will work, since static data areas currently are scanned by the GC.
We've talked about changing this behaviour, however, and requiring
explicit registration of static roots, in order to improve performance
and the possibility of porting to different collectors. So it might not
be a good idea to rely on this behaviour for new CNI code.
>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++
>
Sounds cool. Its good to hear that GCJ is useful for you.
>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.
>>
"new" is overloaded by java::lang::Object. So when you allocate a Java
object, "new" actually calls the GC allocator, not the standard C++ one.
Regards
Bryce.
More information about the Java
mailing list