tags:

views:

98

answers:

4

The examples for JNI i've seen map Java native methods to implementation by C++ global functions. Is there a way to set the native methods implementation to be the member functions of a C++ object instead?

A: 

I don't think that works right away, because the JNI doesn't have a way to know to which C++ object (instance) a method call belongs to. You will have to do the mapping to the correct object manually.

Daff
A: 

It does work for methods though. But you do not want to have to handle exceptions from C++ here.

krico
+1  A: 

JNI doesn't know anything about your C++ classes. It just allows you to implement the methods of your Java classes using native code. The C++ functions you write are the methods of a Java class so it doesn't make sense to simultaneously make them methods of a different C++ class.

If you are worried about namespace pollution you can use RegisterNatives to manually set up the link to the native methods. Doing so would allow you to name the functions the way you want, put your native functions into a namespace, or declare them as static to keep their symbols from being exported. I suppose you could use this approach to link to a static method of a C++ class but I seriously doubt it would make your code any easier to understand, especially if on the Java side the method is non-static.

Tim Kryger
A: 

Simple answer: no. The defined behavior of the JVM is to invoke global functions.

It is not particularly hard to do this for yourself. One way is to have the first JNI function return a long 'handle' that is, in fact, a pointer to an object. Have the other functions invoke methods after casting it back to a pointer.

bmargulies