C++调用JAVA 例子
502_7@ 1 #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
2 #include "platform/android/jni/JniHelper.h"
3
4 int KuNiuLogin(lua_State *lua)
5 {
6 JniMethodInfo methodInfo;
7 auto isOk = JniHelper::getStaticMethodInfo(methodInfo,org/cocos2dx/cpp/AppActivity",0); line-height:1.5!important">sdkLogin()V");
8 if (isOk)
9 {
10 auto activityObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID,methodInfo.methodID);
11 }
12 return 0;
13 }
14 #endif
@H_前提假设:
有这么一个java文件.
org/cocos2dx/cpp/AppActivity.java
这个类有一个sdkLogin的静态共有函数.
class AppActivity {
public static void sdkLogin() {}
};
我们需要通过C++调用上面的JAVA函数 sdkLogin.
JniHelper.h 是cocos2dx引擎自带操作java的头文件,它在Windows平台不起作用.
如果你需要vs的语法提示,你可以把它写在条件编译外面,
这么做会报错,因为里面包含了jni.h文件,这个文件在java虚拟机安装目录可以找到,sans-serif"> 放到vs include目录即可.
@H_502_7@JniHelper::getStaticMethodInfo(methodInfo,0); line-height:1.5!important">");
第一个参数是一个JniMethodInfo类型的参数.
第二个参数指定java文件的路径,sans-serif"> 第三个参数是函数名,sans-serif"> 第四个参数是参数签名. (google有更详细的签名解释).
于是
@H_502_7@auto activityObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID,methodInfo.methodID);
这行就是调用了...
JAVA调用C++例子.
1 extern C" {
2 3 void Java_org_cocos2dx_cpp_JniTestHelper_KuNiuLogin(JNIEnv *env,jobject thiz,jstring jstr)
4 {
5 auto strOpenId = env->GetStringUTFChars(jstr,NULL);
6 env->ReleaseStringUTFChars(jstr,strOpenId);
7 }
8 #endif
9 }