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.

  1. Prepare Java method
  2. 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(""));
    if (context != null) {

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


	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);

()V is type of Java Method. return void, no argument
This is useful website for it ACUCOBOL-GT インターオペラビリティガイド

Call from C++ cocos2d-x


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);


CallStaticVoidMethod is method which returns void. CallStaticIntMethod, etc…
Separate name by return value type.

Java call C++

Use JNI technique.

  1. Prepare Java native method
  2. 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" {

JNIEXPORT void JNICALL Java_com_atmarkplant_cocos2dx_jni_AndroidJNI _update
  (JNIEnv *, jobject, jint);

#ifdef __cplusplus
#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 =;
                // Get All layers

<h3>C++ std::string to jstring</h3>
jstring jname = t.env->NewStringUTF(actionname.c_str());  // actioname is C++ std::string

Argument string