JNI 简单使用
cocos 打包发布android应用经常要集成第三方SDK,有时必须要使用JNI通过C++调用Java方法。
1 2 3
| public static String pay(String index){ return "success"; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include "platform/android/jni/JniHelper.h" #include <jni.h>
#define PAGENAMEPATH "org/cocos2dx/cpp/AppActivity"
JniMethodInfo minfo; bool isHave = JniHelper::getStaticMethodInfo(minfo, PAGENAMEPATH, "pay", "(Ljava/lang/String;)Ljava/lang/String;"); // 验证方法是否存在 if (!isHave) { CCLOG("jni:no method"); } else { CCLOG("jni:has method"); // pay方法参数转换成jstring类型 jstring idx = minfo.env->NewStringUTF("0"); // 调用方法 jstring result = (jstring)minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID, idx); // 把pay方法返回的result转换成string类型 char* rtn = NULL; jclass clsstring = minfo.env->FindClass("java/lang/String"); jstring strencode = minfo.env->NewStringUTF("utf-8"); jmethodID mid = minfo.env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B"); jbyteArray barr = (jbyteArray)minfo.env->CallObjectMethod(result, mid, strencode); jsize alen = minfo.env->GetArrayLength(barr); jbyte* ba = minfo.env->GetByteArrayElements(barr, JNI_FALSE); if (alen > 0) { rtn = (char*)malloc(alen + 1); memcpy(rtn, ba, alen); rtn[alen] = 0; } minfo.env->ReleaseByteArrayElements(barr, ba, 0); // 判断返回结果,进行相应逻辑处理 if(rtn == "1") return; else return; } CCLOG("jni-javamethod finish");
|