<1>C++中头文件声明。
[cpp] view plain copy 在CODE上查看代码片派生到我的代码片
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include “platform/android/jni/JniHelper.h”
#include <android/log.h>
#endif
<2>C++中函数实现(jstring转const char*)。
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //判断当前是否为Android平台 extern "C" { void Java_com_qingxue_gameMyHeroPass_MyHeroPass_testJNIString(JNIEnv* env, jobject thiz , jstring jstr) { const char* str = env->GetStringUTFChars(jstr, NULL); if (str == NULL) { return; } env->ReleaseStringUTFChars(jstr, str); } }
<3>const char*转jstring
[plain] view plain copy 在CODE上查看代码片派生到我的代码片
jstring strencode = env->NewStringUTF(“Hello World”);
<4>Java中函数原型声明。
[java] view plain copy 在CODE上查看代码片派生到我的代码片
public static native void testJNIString(String jstr);
<5>Java中调用本地方法。
[java] view plain copy 在CODE上查看代码片派生到我的代码片
String str = “Hello World”;
testJNIString(str);
==================
<1>c++调用java字符串接受及其返回一个字符串的传递
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)//判断当前是否为Android平台 JniMethodInfo jmi; bool isHave = JniHelper::getStaticMethodInfo(jmi,"com/test/testjni","getName","()Ljava/lang/String;"); if(isHave) { // 调用CallStaticObjectMethod方法会返回一个jobject对象,在前面弄个(jstring)就可以转换成jstring // 然后调用JniHelper提供的便捷方法jstring2string(),直接把jstring转成C++中的string(对源码感兴趣的可以直接去看“cocos2dx/platform/android/jni/JniHelper”中的具体实现) jstring js_pkn = (jstring)jmi.env->CallStaticObjectMethod(jmi.classID,jmi.methodID); //后面继续扩展传递新的参数 std::string str_pkn = JniHelper::jstring2string(js_pkn); } #endif