Java CNI (04 Dec 2002)

A quick lesson in the wonders of how Java and GCC work together.

For quite a while now, the GCJ project has been adding Java support to GCC. It isn't perfect and building your big, using every API Java app with it could be a real pain. But it is getting better. Anyway, this is about working together.

Java has always had JNI for interfacing with other languages (generally C/C++). It works, but it's not exactly clean. GCJ, however, has the CNI which works much more nicely. A small example:

Make up a Java class and have some methods marked as public:

class CNITest {
	public static native int native_call (String a);

	public static void main (String[] args) {
		native_call ("testing");

Build a class file and generate the header from it

gcj -C
gcjh CNITest

Write the native methods in whatever language you like (given that GCC and compile and link it with Java). In this case C++:

#include "CNITest.h

jint CNITest::native_call (jint a)
        return a + 1;

Now build it all:

gcj --main=CNITest -o cni cni.cpp

and it all works. Woo!