如何将cocos2d ValueMap作为HashMap发送到Java?

时间:2017-10-11 08:55:37

标签: java android c++ cocos2d-x

我有cocos2d:: ValueMap

 ValueMap map;
 map["key1"] = "value1";
 map["key2"] = 1;
 map["key3"] = true;

我想将其作为HashMap<String,Object>

发送给Java

所以我编写了以下代码,我生成了jobject hashMapObj,我希望用值填充它:

jclass hashMapClass= jniGetInstance.env->FindClass("java/util/HashMap");
jmethodID hashMapInit = jniGetInstance.env->GetMethodID(hashMapClass, "<init>", "(I)V");
jobject hashMapObj = jniGetInstance.env->NewObject(hashMapClass, hashMapInit, values.size());

//javap -s -p java.util.HashMap  | grep -A 1 put\(
jmethodID hashMapId = jniGetInstance.env->GetMethodID(hashMapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");

for (auto it : map) {   //https://github.com/cocos2d/cocos2d-x/blob/v3/cocos/base/CCValue.h
    switch (it.second.getType()) {
        case cocos2d::Value::Type::BOOLEAN:
            jniGetInstance.env->CallObjectMethod(hashMapObj, hashMapId, "put",
                                                 jniGetInstance.env->NewStringUTF(
                                                         it.first.c_str()),
                                                 it.second.asBool());
            break;
       //...

        default:
            break;
    }
}

我遇到了崩溃:

jniGetInstance.env->CallObjectMethod(
   hashMapObj, 
   hashMapId,
   "put", 
   jniGetInstance.env->NewStringUTF(                                             
               it.first.c_str()),
               it.second.asBool());
  

应用程序中的JNI检测错误:使用无效的jobject 0xd85d4aa0

修改

jniGetInstance.env->CallObjectMethod(hashMapObj, hashMapId, "put","someString", true);

失败并出现同样的错误,因此问题出在hashMapObj

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

更改

jniGetInstance.env->CallObjectMethod(hashMapObj, hashMapId, "put",
    jniGetInstance.env->NewStringUTF(
        it.first.c_str()),
        it.second.asBool());

jniGetInstance.env->CallObjectMethod(hashMapObj, hashMapId,
    jniGetInstance.env->NewStringUTF(it.first.c_str()),
    it.second.asBool());

因为“put”方法只接受2个参数。

还要确保it.second.asBool()返回jboolean - 它与C ++ bool类型不同。