Cocos2d-x C++ JNI
Java, C++
Cocos2d-x is NDK, C++, Android is basically Java.
Sometimes, we want to call Java from C++, and call C++ from Java, How to do that?
C++ call Java
Use Cocos2d-x technique.
Steps
- Prepare Java method
- Prepare Cocos2d method
Java the package name is com.atmarkplant.cocos2dx class name is AndroidAction
public static void goGoogle() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (context != null) {
context.startActivity(intent);
}
}
C++ Header AndroidAction.h
#ifndef __REWARD_ACTION_H__
#define __ANDROID_ACTION_H__
#include "cocos2d.h"
#include <jni.h>
#include <platform/android/jni/JniHelper.h>
class AndroidAction
{
public:
AndroidAction(void);
~AndroidAction(void);
static void google();
};
#endif // __ANDROID_ACTION_H__
C++ source code AndroidAction.cpp
#include "AndroidAction.h"
#define CLASS_NAME_JNI "com/atmarkplant/cocos2dx/AndroidAction"
void AndroidAction::goGoogle() {
cocos2d::JniMethodInfo t;
if (cocos2d::JniHelper::getStaticMethodInfo(t, CLASS_NAME_JNI, "goGoogle", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
()V is type of Java Method. return void, no argument
This is useful website for it ACUCOBOL-GT インターオペラビリティガイド
Call from C++ cocos2d-x
AndroidAction::goGoogle();
Example of argument (I)V
void AndroidAction::updateScore(int score) {
cocos2d::JniMethodInfo t;
if (cocos2d::JniHelper::getStaticMethodInfo(t, CLASS_NAME_APP, "updateScore", "(I)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, score);
t.env->DeleteLocalRef(t.classID);
}
}
Take
CallStaticVoidMethod is method which returns void. CallStaticIntMethod, etc…
Separate name by return value type.
Java call C++
Use JNI technique.
- Prepare Java native method
- Prepare JNI C++ method
Java Native method
package com.atmarkplant.cocos2dx.jni;
public class AndroidJNI {
public static native void update(int count); // This is declaration of C++ native method
}
C++ Header AndroidJni.h
#include <jni.h>
#ifndef __ANDROID_JNI__
#define __ANDROID_JNI__
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_com_atmarkplant_cocos2dx_jni_AndroidJNI _update
(JNIEnv *, jobject, jint);
#ifdef __cplusplus
}
#endif
#endif __ANDROID_JNI__
C++ Source code AndroidJni.cpp
#include "AndroidJni.h"
JNIEXPORT void JNICALL Java_com_atmarkplant_cocos2dx_jni_AndroidJNI _update
(JNIEnv *env, jobject obj, jint count) {
Vector<cocos2d::Node *> layers = CCDirector::sharedDirector()->getRunningScene()->getChildren();
for (int i=0; i < layers.size(); i++) {
Node *node = layers.at(i);
// Get All layers
}
}
[/cpp]
<h3>C++ std::string to jstring</h3>
[cpp]
jstring jname = t.env->NewStringUTF(actionname.c_str()); // actioname is C++ std::string
Argument string
(Ljava/lang/String;)V

Very grateful for this lesson!