标签:cocos2d-x3.1 jnihelper c++调java
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include <jni.h> #include "../../cocos2d/cocos/platform/android/jni/JniHelper.h" //这里的路径要根据你工程的实际情况进行更改 #include <android/log.h> #if 1 #define LOG_TAG "JniHelper" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #else #define LOGD(...) #endif #endif(3)在下面函数中添加如下代码:
void HelloWorld::menuCloseCallback(Ref* pSender) { #if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo info; //getStaticMethodInfo判断java定义的静态函数是否存在,返回bool bool ret = JniHelper::getStaticMethodInfo(info,"org/cocos2dx/cpp/TestJni","func1","()V"); if(ret) { log("call void func1() succeed"); //传入类ID和方法ID,小心方法名写错,第一个字母是大写 info.env->CallStaticVoidMethod(info.classID,info.methodID); } ret = JniHelper::getStaticMethodInfo(info,"org/cocos2dx/cpp/TestJni","func2","()I"); if(ret) { log("call int func2() succeed"); jint iret = info.env->CallStaticIntMethod(info.classID,info.methodID); log("func2 return = %d",iret); } ret = JniHelper::getStaticMethodInfo(info,"org/cocos2dx/cpp/TestJni","func3","(I)Ljava/lang/String;"); if(ret) { log("Call int func3(int) succeed"); jobject jobj = info.env->CallStaticObjectMethod(info.classID,info.methodID,1438); } ret = JniHelper::getStaticMethodInfo(info,"org/cocos2dx/cpp/TestJni","func4","(Ljava/lang/String;)Ljava/lang/String;"); if(ret) { log("call string func4(string) succeed"); jobject para = info.env->NewStringUTF("haha"); jstring jstr = (jstring)info.env->CallStaticObjectMethod(info.classID,info.methodID,para); std::string text = JniHelper::jstring2string(jstr); log("%s",text.c_str()); } ret = JniHelper::getStaticMethodInfo(info,"org/cocos2dx/cpp/TestJni","func5","(II)I"); if(ret) { log("call int func5(int a, int b) succeed"); jint iret = info.env->CallStaticIntMethod(info.classID,info.methodID,1,2); log("return value is %d",iret); } #endif }这样点击HelloWorld中的关闭按钮,即可在控制台打印出上面的信息。
package org.cocos2dx.cpp; import android.R.integer; import android.util.Log; public class TestJni { public static void func1() { Log.e("hello", "world"); } public static int func2() { return 12345; } public static String func3(int i) { String str = "get int value:" + i; Log.e("yu", str); return str; } public static String func4(String str) { Log.e("func4", "str"); return str; } public static int func5(int a,int b) { int c = a + b; Log.e("func5", "a+b"); return c; } }(4)至此,我们即可进行编译了,对了,在Xcode工程中,HelloWorld.cpp文件中getStaticMethodInfo中第2个参数的路径是怎么回事儿呢。如果一直跟着我的做,此时该路径为org/cocos2dx/cpp/TestJni。第三个参数为TextJni.java中的静态函数。其他参数的具体含义自行百度。这里主要讲路径是怎么回事。
Cocos2d-x3.1通过JniHelper调用Java类中静态函数
标签:cocos2d-x3.1 jnihelper c++调java
原文地址:http://blog.csdn.net/yuxikuo_1/article/details/39552639