How to force the JNI method to call non-static when using native C ++ objects?

I have the following C ++ code for the JNI shell:

#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 com.map.Map.openMapNative declared as static, which means that I can manage one map at a time. How can I change this code in C ++ so that map_container* map becomes non-static and belongs to the exact instance of the com.map.Map class? map_container is a fully C ++ class and is not reflected in Java.

+4
source share
3 answers

I use SWIG to create all the necessary shell code. You simply define the classes and functions that you want to wrap in the interface definition file, and let SWIG create all the necessary C ++ and Java codes for you. Highly recommended! Manually writing JNI code is just too boring and prone to IMHO errors. See SWIG docs for Java , it is very easy to use.

+2
source

If you specified Map.openMapNative as "static native" in the Java source, then the current declaration is misleading because the second argument is a reference to the Map class (must be "jclass clazz" and not "jobject" Thiz). Doesn't have values ​​since you are not using "thiz" and each jclass is a jobject.

The way you do this non-static is to remove the β€œstatic” from the declaration on the Java side and start using β€œtees” to access instance members.

+2
source

Maybe a little late, but this cookbook is priceless here!

http://thebreakfastpost.com/2012/01/23/wrapping-ac-library-with-jni-part-1/

At first glance, and depending on what you need, SWIG may be meta-redundant!

0
source

Source: https://habr.com/ru/post/1335174/


All Articles