Wednesday, 15 August 2012

java - use c++ template to generate JNI functions -



java - use c++ template to generate JNI functions -

i want utilize c++ template generate slot functions , register these functions jvm java code can call, like:

template<typename arg1> void bind_native(const char* classname, const char* staticmethodname, function<void(arg1)>* slotfunc) { jninativemethod sig; sig.name = staticmethodname; sig.signature = wrapper<void(arg1)>::get().getsignature(); sig.fnptr = wrapper<void(arg1)>::get().getslotfunc(slotfunc); // register jni.. } // bind our native function java. function<void(int)> cppintfunc = [](int intfromjava) { printf("called java"); }; bind_native("myclass", "mycppmethod", &cppintfunc); // can bind different functions same signature jni. function<void(int)> cppintfunc1; function<void(int)> cppintfunc2; bind_native("myclass", "mycppmethod1", &cppintfunc1); bind_native("myclass", "mycppmethod2", &cppintfunc2); // in java code: class myclas { private static native mycppmethod(int i); private static native mycppmethod1(int i); private static native mycppmethod2(int i); }

but question is, same template generate same function, can not distinguish method called in jni hence can not original slot function back:

template<typename arg1> struct wrapper { void* getslotfunc(function<void(arg1)>* slotfunc) { // how map slotfunc staticjnifunc? homecoming staticjnifunc; } static jnicall void staticjnifunc(jnienv* e, jclass c, arg1 param1) { // how slotfunc here? (*slotfunc)(param1); } };

maybe need find way running jmethodid jni?

add integer template parameter create unique templates , utilize macro line auto generate integer (see note 1):

// note 1 template<int methodid, typename arg1> struct wrapper { map<string, slotfuncptr> funmap; void* getslotfunc(const char* classname, function<void(arg1)>* slotfunc) { funcmap[classname] = slotfunc; // note 2 homecoming staticjnifunc; } static jnicall void staticjnifunc(jnienv* e, jclass c, arg1 param1) { auto* slotfunc = funcmap[getclassname(c)]; // note2 (*slotfunc)(param1); } }; // note1 #define bind_native(name,f) bind_native_<__line__>(name,f)

then bind_native(...) can generate different static method methods same signature. , in case same signature functions bound same line number, can distinguish them jclass(see note2).

java c++ templates binding jni

No comments:

Post a Comment