在cocos2dx程序里面如果需要接入第三方SDK的话,Jni与c++的通信是必不可少的,所以我这里就介绍一下嘴基本的通信,分为:无参无返回值,有参无返回值,无参有返回值,有参有返回值四类,话不多说,直接上代码
这个是在我们的cocos程序里面的:
需要先引入头文件:
#include "platform/android/jni/JniHelper.h"
#include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include <jni.h>
void HelloWorld::JniTest()//无参无返回值
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "com/cocos2dx/org/JniiTest", "MyTest", "()V"))
{
t.env->CallStaticVoidMethod(t.classID, t.methodID/*, payId, price*/);
CCLOG("the function is exist");
}
#endif
}
void HelloWorld::JniTest1()//有参无返回值
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
CCLOG("00000001");
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "com/cocos2dx/org/JniiTest", "CanshuTest", "(Ljava/lang/String;)V"))
{
CCLOG("00000002");
jstring str=t.env->NewStringUTF("msg");//传入的meg字符串
CCLOG("00000003");
t.env->CallStaticVoidMethod(t.classID, t.methodID,str/*, payId, price*/);
CCLOG("00000004");
t.env->DeleteLocalRef(t.classID);
CCLOG("the function is exist");
}
#endif
}
void HelloWorld::JniTest2()//无参有返回值
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "com/cocos2dx/org/JniiTest", "fanhuizhiTest", "()Ljava/lang/String;"))
{
jstring jstr=(jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID/*, payId, price*/);
std::string str=JniHelper::jstring2string(jstr);
//CCLog("string is :%s ",str);
// t.env->DeleteLocalRef(t.classID);
CCLOG("return string is: %s",str.c_str());
}
#endif
}
void HelloWorld::JniTest3()有参有返回值
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "com/cocos2dx/org/JniiTest", "Test", "(II)I"))
{
jint x=10;
jint y=2;
jint jRes=t.env->CallStaticIntMethod(t.classID, t.methodID,x,y);
// t.env->DeleteLocalRef(t.classID);
CCLOG("return Int is: %d",jRes);
}
#endif
}
下面是在我们eclipse里面的工程目录下面的src下面的com/cocos2dx/org/J下面的JniiTest文件夹,大家可以找到相应的自己的文件夹,然后加入下面代码:
public static void MyTest(){
Log.i("tag", "无参无返回值");
}
public static void CanshuTest(String str){
Log.i("tag", "有参无返回值 参数是:"+str);
}
public static String fanhuizhiTest(){
Log.i("tag", "无参有返回值");
return "return meg";
}
public static int Test(int x,int y){
Log.i("tag", "有参有返回值");
return x+y;
}
这样我们运行程序时就会在eclipse的LogCat里面看到相应的打印,这里我截取一个打印的第一个函数图片:
这里需要注意的是我们需要在真机环境或者是模拟器环境上面才能运行。
到这里Jni与c++的基本的通信就介绍完了,大家轻喷
------------蛋蛋