Finalization and CNI
Bryce McKinlay
bryce@mckinlay.net.nz
Wed Jun 11 01:29:00 GMT 2003
On Wednesday, June 11, 2003, at 08:59 AM, Craig A. Vanderborgh wrote:
> include <gcj/cni.h>
> #include <stdio.h>
> #include "HelloWorld.h"
>> void HelloWorld::print() {
> printf("Hello, world from CNI!\n");
>> void *alloc = new char[1024];
> }
>> Presumably "alloc" is going to be leaked, correct?
Correct. If your using "new" in CNI code, Java objects are allocated by
the garbage collector just like they would be in Java, but non-Java
objects are allocated on the non-garbage collected heap in the same was
as they would be in C++.
> Is the correct thing
> to do to put the deallocation stuff into the destructor for the
> HelloWorld class? Would my destructor then get called at some point?
That should work. Just be careful not to leave pointers to Java objects
in the C++ heap, as while objects allocated there are not eligible for
collection, they will be scanned for pointers by the collector.
As an alternative, consider using GCJ's _Jv_AllocBytes: see
http://gcc.gnu.org/onlinedocs/gcc-3.3/gcj/Object-allocation.html
For example:
char *alloc = (char *)_Jv_AllocBytes(1024 * sizeof(char))
will give you a garbage-collected "alloc" whose contents is not scanned
by the collector. You should only store "native" data in an object
allocated by this function - not reference to Java objects - or the
collector could end up freeing Java objects that are still reachable
from your CNI code.
Bryce.
More information about the Java
mailing list