Last active
August 29, 2015 14:14
-
-
Save maple-nishiyama/5907732ba41efa441453 to your computer and use it in GitHub Desktop.
Cocos2d-x Android でネイティブの別スレッドからJNIを触ると落ちる件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool HelloWorld::init() | |
{ | |
if ( !Layer::init() ) | |
{ | |
return false; | |
} | |
auto ud = UserDefault::getInstance(); | |
ud->setStringForKey("aaa", "ほげほげほげ"); | |
ud->flush(); | |
auto th = std::thread([this](){ | |
auto ud = UserDefault::getInstance(); | |
std::string hoge = ud->getStringForKey("aaa"); | |
CCLOG("ほげ = %s", hoge.c_str()); | |
}); | |
th.detach(); | |
return true; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 解決した | |
bool HelloWorld::init() | |
{ | |
if ( !Layer::init() ) | |
{ | |
return false; | |
} | |
auto ud = UserDefault::getInstance(); | |
ud->setStringForKey("aaa", "ほげほげほげ"); | |
ud->flush(); | |
auto th = std::thread([this](){ | |
// スレッドの開始直後にこのスレッドをJVMに接続する | |
JNIEnv *env = 0; | |
// get jni environment | |
if (JniHelper::getJavaVM()->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { | |
CCLOG("Failed to get the environment using GetEnv()"); | |
} | |
if (JniHelper::getJavaVM()->AttachCurrentThread(&env, 0) < 0) { | |
CCLOG("Failed to get the environment using AttachCurrentThread()"); | |
} | |
// JNI を使った処理をする | |
auto ud = UserDefault::getInstance(); | |
for (int i = 0; i < 100000; i++) { | |
std::string hoge = ud->getStringForKey("aaa"); | |
CCLOG("ほげ = %s", hoge.c_str()); | |
} | |
// スレッド終了直前にこのスレッドをJVMから切り離す | |
JniHelper::getJavaVM()->DetachCurrentThread(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
スレッド開始したらすぐにJVMに接続、
スレッド終了前にJVMから切断
でOKぽい