cocos2d-x之C++ 调用Java函数并接收返回值

前端之家收集整理的这篇文章主要介绍了cocos2d-x之C++ 调用Java函数并接收返回值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参考:http://blog.csdn.net/xiaominghimi/article/details/7602984
</pre><pre code_snippet_id="1607324" snippet_file_name="blog_20160312_3_5324342" name="code" class="cpp">//java中string转C++中string
<pre name="code" class="html">#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
//jstring to char*
std::string jstringTostring(JNIEnv* env,jstring jstr)
{
	char* rtn = NULL;
	jclass clsstring = env->FindClass("java/lang/String");
	jstring strencode = env->NewStringUTF("utf-8");
	jmethodID mid = env->GetMethodID(clsstring,"getBytes","(Ljava/lang/String;)[B");
	jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr,mid,strencode);
	jsize alen = env->GetArrayLength(barr);
	jbyte* ba = env->GetByteArrayElements(barr,JNI_FALSE);
	if (alen > 0)
	{
		rtn = (char*)malloc(alen + 1);
		memcpy(rtn,ba,alen);
		rtn[alen] = 0;
	}
	env->ReleaseByteArrayElements(barr,0);
	std::string stemp(rtn);
	free(rtn);
	return stemp;
}
#endif

//调用手机信息接口
std::string callJinPhoneNum() {
	std::string strNum;
	//Android:调用手机号码接口
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	JniMethodInfo minfo;
	bool isHave;
	isHave = JniHelper::getStaticMethodInfo(minfo,PACKAGE_NAME,"getPhoneNum","()Ljava/lang/String;");
	if (!isHave) {
		log("JNI:exitGame method is not exist");
	}
	else{
		jstring jsNum = (jstring)minfo.env->CallStaticObjectMethod(minfo.classID,minfo.methodID);
		strNum = jstringTostring(minfo.env,jsNum);
	}
#endif
	return strNum;
}
void callJinTime(std::string strTime) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo minfo; bool isHave; isHave = JniHelper::getStaticMethodInfo(minfo,"getTime","(Ljava/lang/String;)V"); if (!isHave) { log("JNI:exitGame method is not exist"); } else{ jstring jstr = minfo.env->NewStringUTF(strTime.c_str()); minfo.env->CallStaticObjectMethod(minfo.classID,minfo.methodID,jstr); } #endif }

猜你在找的Cocos2d-x相关文章