How do I make JNI method call not static when using native C++ objects?
I have the following JNI wrapper C++ code:
#include "map_container.h"
extern "C" {
JNIEXPORT void JNICALL Java_com_map_Map_openMapNative(JNIEnv* env, jobject thiz, jstring path);
};
static map_container* map = NULL;
void Java_com_map_Map_openMapNative(JNIEnv* env, jobject thiz, jstring path)
{
const char* filename_utf8 = env->GetStringUTFChars(path, false);
if ( mapview )
{
delete mapview;
mapview = NULL;
}
mapview = new map_container((char*)filename_utf8);
if (filename_utf8)
{
env->ReleaseStringUTFChars(path, filename_utf8);
}
}
and have com.map.Map.openMapNative
declared as static which means that I can operate one map a开发者_Python百科t a time. How do I modify this C++ code so that map_container* map
becomes not static and belongs to the exact instance of com.map.Map
class? map_container
is totally C++ class and has no reflection in Java.
I'm using SWIG to generate all the necessary wrapper code. You simply define the classes and functions you want to wrap in an interface definition file, and let SWIG create all the required C++ and Java code for you. Highly recommended! Writing JNI code by hand is just way too boring and error-prone IMHO. See the SWIG docs for Java, it's very easy to use.
If you have declared Map.openMapNative as "static native" in the Java source, then the current declaration is misleading, because the second argument is actually a reference to the Map class (should be "jclass clazz" rather than "jobject thiz"). Doesn't really matter, since you're not using "thiz", and every jclass is a jobject.
The way you make this non-static is to remove the "static" from the declaration on the Java side, and start using "thiz" to access members of the instance.
It might be a little late, but this cookbook here is invaluable!
http://thebreakfastpost.com/2012/01/23/wrapping-a-c-library-with-jni-part-1/
At first glance, and depending that you need, SWIG might be meta-overkill!
精彩评论