Aer*_*alo 5 c++ java java-native-interface
我有一个 JAVA 调用的 JNI 函数,它需要构建并返回一个 HashMap。映射的键是 'String',相应的值是 'boolean' 或 'Boolean'(任何一个都可以,只要它有效)。使用我拥有的当前代码(如下),该字符串已成功添加到返回的地图中,并可在 Java 中访问。但是,当尝试访问 JAVA 中的值时,它会出现 null。
jclass mapclass = env->FindClass("java/util/HashMap");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
env->CallObjectMethod(roster_return, putmeth, env->NewStringUTF(iter->second.name.c_str()), (jboolean)iter->second.isfriend);
iter++;
}
Run Code Online (Sandbox Code Playgroud)
我试过生成一个布尔对象,但我似乎无法弄清楚如何创建一个新对象。我已经尝试了以下代码,但它在布尔值“init”的“GetMethodID”上出错。
jclass mapclass = env->FindClass("java/util/HashMap");
jclass boolclass = env->FindClass("java/lang/Boolean");
jmethodID initmeth = env->GetMethodID(mapclass, "<init>", "()V");
//-----------------It errors on the next line-----------------------
jmethodID initbool = env->GetMethodID(boolclass, "<init>", "()V");
jmethodID putmeth = env->GetMethodID(mapclass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jobject roster_return = env->NewObject(mapclass, initmeth);
int roster_map_size;
std::map<std::string, RosterItem>* roster_map = GetRosterMap();;
std::map<std::string, RosterItem>::iterator iter;
if (!roster_map || roster_map->size() < 1)
return roster_return;
iter = roster_map->begin();
while (iter != roster_map->end())
{
LOGE("adding contact: %s", iter->second.jid.Str().c_str());
//---Not sure what to pass in the next function here for the fourth argument---
env->CallObjectMethod(roster_return, putmeth, env->NewStringUTF(iter->second.name.c_str()), (jboolean)iter->second.isfriend);
iter++;
}
Run Code Online (Sandbox Code Playgroud)
小智 3
老问题,但我今天也在寻找这个。当您在不同语言之间切换时,很容易忘记 Java 的原始boolean类型与可为 null 的Boolean对象类型之间存在差异。Map 的值必须是一个 Object,因此Boolean是必需的。
因此,要创建一个新Boolean对象:
// Sample C++ boolean variable you want to convert to Java:
bool someBoolValue = true;
// Get the Boolean class
jclass boolClass = env->FindClass("java/lang/Boolean");
// Find the constructor that takes a boolean (note not Boolean) parameter:
jmethodID boolInitMethod = env->GetMethodID(boolClass, "<init>", "(Z)V");
// Create the object
jobject boolObj = env->NewObject(boolClass,
boolInitMethod,
someBoolValue ? JNI_TRUE : JNI_FALSE);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3210 次 |
| 最近记录: |