live2dream95
live2dream95

Reputation: 6067

Mapping Java Native Methods to C++ Member Functions

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?

Upvotes: 2

Views: 1950

Answers (5)

zOlive
zOlive

Reputation: 1778

Not with JNI alone.

You can, however, use a library such as BridJ, which supports binding native Java methods to C++ methods (your Java class must have the same name as the C++ class and derive from CPPObject, amongst other things).

Upvotes: 0

Tim Kryger
Tim Kryger

Reputation: 11246

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.

Upvotes: 3

bmargulies
bmargulies

Reputation: 100050

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.

Upvotes: 1

krico
krico

Reputation: 5728

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

Upvotes: 0

Daff
Daff

Reputation: 44215

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.

Upvotes: 0

Related Questions