JNI Callbacks

Someone at work asked me about doing JNI. They want to make a java wrapper for a scene graph they have made. The question is - Can you have C code calling Java? IE - Everytime an event happens, the java code needs to run. It ‘seems’ like an inversion of the normal JNI stuff, where you call a java method and it in turn runs native code.

Can anyone speak to this?

Any sites where I would find good info?

Regards,
Dr. A>

Yeah, it’s not hard. The Java JNI reference book has it all in detail.

Cas :slight_smile:

Yup as Cas says, the hardest thing is working out the method “signiture” of the method you are calling so you can get a Method object from the VM to call through (and yes thisi so n the C side, you get a sturcture that represents the method from the VM.)

In fact JNI is totally bi-directional. You can even launch a new VM from inside of a C program using JNI.

A general JNI caution. Passing a lot of data between the Java heap and the C heap can be quite slow. If thats what you want to do you might want to investiagte Native ByteBuffers (which a modern JNI book should also talk about) which is a way to allow the Java side to interract directly with C-heap located data.

Oh, and another thing, which took me a while to figure out! - if the calling thread is NOT from the VM then you need to attach it before calling into the VM using AttachCurrentThread.