Call compiled Java from C/C++?
Jeff Sturm
jsturm@sigma6.com
Fri Oct 1 09:20:00 GMT 1999
Andrew Haley wrote:
>
> > Date: Fri, 01 Oct 1999 09:02:19 +0200
> > From: Vito BAGGIOLINI <Vito.nospam.Baggiolini@cern.ch>
> >
> > Hello,
> >
> > I understand that CNI is primarily intended to call C/C++ routines from
> > a Java 'main' program.
> >
> > But is the opposite possible, i.e. to call a compiled Java code from
> > a C/C++ 'main' program? (With JNI this is possible, but quite clumsy).
>
> The Java runtime garbage collector scans the stack and assumes that
> any pointers it finds which point into the Java heap will point to
> Java data structures with valid Java metadata fields. C++ classes
> don't have the metadata fields. The gc also knows that if no Java
> pointers refer to a gc allocated structure it may be reclaimed.
C++ objects don't have metadata, but they don't live in the Java (GC-ed)
heap anyway. Static C++ objects in the data segment and heap-allocated
objects will be scanned for pointers. Objects allocated with `new' live
in the standard (malloc'ed) heap and are ignored by the collector, so
they should not keep pointers to Java objects.
> If you learn about how the gc and metadata work together you can
> certainly design a solution that works, but it may be quite tricky.
> If you arrange for no C++ struct ever to contain a pointer to a gc
> allocated Java object you may be OK, but I wouldn't recommend it.
The metadata isn't important; the boehm-gc collector can scan memory
conservatively if it doesn't know the structure of an object. But
unless you enable GC for C++ object allocation (I have no idea how well
that would work with libgcj), it isn't safe, as Andrew says.
But like it or not, many applications require direct invocation of Java
objects... web browsers with an embedded VM for example. I think it
would be a good idea to allow it in the CNI specification, even with the
pitfalls. GC-enabled objects must be able to coexist with non-GC
objects; it's a known (and documented) problem.
--
Jeff Sturm
jsturm@sigma6.com
More information about the Java
mailing list