The examples for JNI i've seen map Java native methods to implementation by C++ global functions.开发者_JS百科 Is there a way to set the native methods implementation to be the member functions of a C++ object instead?
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.
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.
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.
It does work for methods though. But you do not want to have to handle exceptions from C++ here.
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).
精彩评论