Skip to content

Instantly share code, notes, and snippets.

@maple-nishiyama
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maple-nishiyama/5907732ba41efa441453 to your computer and use it in GitHub Desktop.
Save maple-nishiyama/5907732ba41efa441453 to your computer and use it in GitHub Desktop.
Cocos2d-x Android でネイティブの別スレッドからJNIを触ると落ちる件
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;
}
// 解決した
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();
});
@maple-nishiyama
Copy link
Author

スレッド開始したらすぐにJVMに接続、
スレッド終了前にJVMから切断
でOKぽい

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment