LoginSignup
23
25

More than 5 years have passed since last update.

cocos2d-x C++からJNIでJavaを呼ぶ方法

Last updated at Posted at 2014-03-26

需要があるかわからないけど
JNI呼び出しは色んな方法があるとおもいますが
cocos2d-xらしい? 呼び方を

JNIとは

Javaとネイティブ(C言語等)を橋渡しするものです

お題

SDカードのディレクトリgetExternalStorageDirectory() のパスを返すだけの
簡単なものを作ります

java

FileUtil.java
package com.murasamelabo.Android.Util;

import android.os.Environment;

public class FileUtil {
    public static String getExternalStorageDirectory(){
        String s="";
        s = Environment.getExternalStorageDirectory().getPath();
        return(s);
    }
}

パッケージ名: com.murasamelabo.Android.Util
クラス名: FileUtil
メソッド名 static String getExternalStorageDirectory()

C++

生JNIでもいいけど、cocosライブラリのccdandroidAndroidJavaEngine.cpp を参考に cocos流儀で

bind.h
#include "bind.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <string>
#include <android/log.h>

namespace JavaBind
{

std::string getExternalStorageDirectory()
{ 
    std::string str;

    cocos2d::CCLog("getExternalStorageDirectory::start");

    cocos2d::JniMethodInfo methodInfo;
    // Javaのメソッドを探す
    cocos2d::JniHelper::getStaticMethodInfo( methodInfo, "com/murasamelabo/Android/Util/FileUtil",  "getExternalStorageDirectory", "()Ljava/lang/String;" );

    // メソッド呼び出し。今回はStatic関数かつ、String型が戻り値なので CallStaticObjectMethod を使う
    jstring jpath  = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID);

    // お約束の文字列変換
    const char* npath = methodInfo.env->GetStringUTFChars(jpath, NULL);
    str = npath;

    // 解放
    methodInfo.env->ReleaseStringUTFChars(jpath, npath);
    methodInfo.env->DeleteLocalRef(methodInfo.classID);
    cocos2d::CCLog("getExternalStorageDirectory::fin:%s", str.c_str() );

    return str;
}

}

まとめ

生でJNI触った人ならわかると思いますが、かなり簡単になってますね

C++ゲンガーとしては、リソースの解放あたりを unique_ptrで出来ないかとか
もっとラップして template使って 便利にしたいとか欲望が出ますね

まー とりあえず、サンプルで。

23
25
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
23
25