android ndk - Subclass a C++ abstract class in Java using JNI -
i have c++ library have use in existing android implementation. i'm using android ndk , using c++ classes via jni.
however, not able find how subclass c++ abstract class in java using jni.
problems face: aim provide java implementation virtual methods in c++ subclassing abstract c++ class. have loaded native library , i'm trying declare native methods. c++ methods have keyword 'virtual'. when declare native functions in java after loading c++ library, 'virtual' not recognized. wrong here?
any appreciated. i'm newbie jni. in advance.
let's consider have c++ class:
class ivehicle { public: virtual void run() {}; // not-pure virtual here simplicity of wrapper, pure (see end of post) virtual int getsize() const; // want reuse in java };
we want create class bot
in java extends class ivehicle
in sense calls super
invoke c++ code ivehicle::getsize()
and, c++ point of view, can use instances of bot
ivehicle*
variables. that's tough since c++ provides no built-in functionality reflection.
here 1 possible solution.
to use c++ class in java need generate java wrapper, i.e:
class ivehicle { public void run() { native_run(); } public int getsize() { return native_getsize(); } private native void native_run(); private native int native_getsize(); // typecasted pointer in c++ private int nativeobjectholder; // create c++ object native static private int createnativeobject(); }
the usage in java simple:
class bot extends ivehicle { public int getsize() { if ( condition ) return 0; // call c++ code return super.getsize(); } }
however, there c++ part code:
static jfieldid gnativeobjectholderfieldid; jniexport void jnicall java_com_test_ivehicle_run( jnienv* env, jobject thiz ) { int value = env->getintfield(thiz, gnativeobjectholderfieldid); ivehicle* obj = (ivehicle*)obj; // todo: add checks here, null , dynamic casting obj->run(); }
the similar code getsize()
.
then creating instance of java's bot
have call createnativeobject()
, assign returned value nativeobjectholder
field.
jniexport int jnicall java_com_test_ivehicle_createnativeobject( jnienv* env, jobject thiz ) { ivehicle* obj = new ivehicle; return (int)obj; }
so, scheme. make work need add destruction code , parse c++ classes generate glue code.
added:
in case ivehicle
abstract have generate non-abstract wrapper able instantiate:
class ivehicle { virtual void run() = 0; } class ivehicle_wrapper: public ivehicle { virtual void run() { error("abstract method called"); }; }
and instantiate ivehicle_wrapper
in createnativeobject()
. vuala! have inherited abstract c++ class in java.
Comments
Post a Comment