LoginSignup
0
0

More than 5 years have passed since last update.

cocos2dxでcppからJavaのコードを実行

Last updated at Posted at 2019-03-08

環境

cocos2dx 3.17 (JavaScript)
Android

問題

cocos2dxのAndroidでネイティブといえばJavaでコードを書くが、使用するライブラリによってはcppを触らなくてはならない。
js -> java -> cpp という流れ。
逆にネイティブからjsの関数を実行するしくみについて、java -> js はあるが、cpp -> js をしたい。
古いcocos2djsではScriptingCore::evalString(code)を使用していた。
しかしcocos2dxをアップデートしていたら、これがcrashする。

crash例

https://github.com/cocos2d/cocos2d-x/issues/17718
https://github.com/cocos2d/cocos2d-x/issues/13807

いろいろ調べると、JniHelperを使うといいようだ。

呼び出し例

以下のように実装して、cpp -> java ( -> javascript)が実現できた。

実装

#include "platform/android/jni/JniHelper.h"

void executeJavaScript()
{
    cocos2d::JniMethodInfo t;

    if (cocos2d::JniHelper::getStaticMethodInfo(t,
                                       "jp/example/java",       // Javaのクラス
                                       "executeJs",             // Javaのメソッド名(static)
                                       "(Ljava/lang/String;)V"  // 引数
    )) {

        // jstring - C++ representation of Java String
        // JSのメソッド名を文字列で書いて変換
        jstring stringArg = t.env->NewStringUTF("javascriptMethod('arg')");

        // call the method, with arguments
        t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0