文字列受け渡し
class Hello { companion object { init { System.loadLibrary("Hello") } } external fun printHello() external fun printNative(str:String, len:Int); } fun main(args: Array<String>) { Hello().printHello() val str = "hello form kotoln" Hello().printNative(str, str.length) }
でcpp側は
#include "Hello.h" #include <iostream> #include <string> extern "C" { JNIEXPORT void JNICALL Java_Hello_printHello (JNIEnv *env, jclass obj) { std::cout << "hello cpp" << std::endl; } JNIEXPORT void JNICALL Java_Hello_printNative (JNIEnv *env, jclass obj, jstring str, jint len) { /// charに変換 jboolean iscopy; const char* msgStr = env->GetStringUTFChars(str, &iscopy); char* copiedChars = strdup(msgStr); env->ReleaseStringUTFChars(str, msgStr); env->DeleteLocalRef(str); printf("%s\n", copiedChars); } }
でいけた。 が、おそらくこの辺の文字コードの話がいるはず…。
Java とか Android (DEX) の MUTF-8 (Modified UTF-8) って何者よ?っていう話 - bearmini's blog
とか
java, a unicode char will be encoded with 4 bytes (utf16). jstring will container characters utf16 std::string in c++ is essentially a string of bytes, not characters,not characters we have convert utf16 to bytes.
とか
- 返却値
class Hello { companion object { init { System.loadLibrary("Hello") } } external fun printHello() external fun printNative(str:String, len:Int): Boolean; } fun main(args: Array<String>) { Hello().printHello() val str = "hello form kotoln" val ret = Hello().printNative(str, str.length) println("ret = " + ret) }
#include "Hello.h" #include <iostream> #include <string> extern "C" { JNIEXPORT void JNICALL Java_Hello_printHello (JNIEnv *env, jclass obj) { std::cout << "hello cpp" << std::endl; } JNIEXPORT jboolean JNICALL Java_Hello_printNative (JNIEnv *env, jclass obj, jstring str, jint len) { /// charに変換 jboolean iscopy; const char* msgStr = env->GetStringUTFChars(str, &iscopy); char* copiedChars = strdup(msgStr); env->ReleaseStringUTFChars(str, msgStr); env->DeleteLocalRef(str); printf("%s\n", copiedChars); return true; } }