简体   繁体   中英

Getting Java object to C++ via JNI (Cocos2dx)

I've ran into a problem where I need to gain access to a custom java class in order to bind it to a custom C++ class (I'm porting a framework for Android).

I've done things such as this:

        bool Myclass_Android::getBoolean() {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
            cocos2d::JniMethodInfo methodInfo;
            if(cocos2d::JniHelper::getStaticMethodInfo(methodInfo, classInfo, "methodname", "()Z") == true){
                CCLOG("method exists");
                methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID);
            }else{
                CCLOG("method doesn't exist");
            }
#endif
        }

Pastebin: http://pastebin.com/y50nJzvR

which retrievs a boolean from the Android framework. Can I do similiar like above but with a whole custom Java class and gain access to it's members?

Just to be clear. The method I wanna use should return a custom C++ class which I've created. I just need to gain access to the Java object in the scope of the method and bind it's members to the C++ class.

I've seen some JNIEXPORT void JNICALL stuff but I can't seem to understand them or get imports for such stuff to work properly.

It would be great if the method used above would work for custom classes aswell and it would be a life saver.

Thanks in advance!

I managed to solve this by using these methods:

jclass myClass = methodInfo.env->FindClass("com/your/package/class");

Which get's a reference to the actual Java custom object you want to work

jfieldID someId = methodInfo.env->GetFieldID("com/your/package/class", "someId", "J");

Which will fetch the field you want to work with. In this case a Long (J). Then to actually make this to usage you'd want to get the object (in this case a object inside the class specified above):

jobject obj = (jobject) methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID);

And finally to get the objects field value from Java to C++ you'd use this:

long _someId = (long) methodInfo.env->GetLongField(obj, someId);

PS, I'm the author. Didn't have time to switch account since I'm currently stationed elsewere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM