JNI:创建HashMap

时间:2011-01-30 16:34:58

标签: java-native-interface hashmap

如何在JNI中创建HashMap对象?

5 个答案:

答案 0 :(得分:18)

以下是代码,您需要修改才能工作

jclass mapClass = (*env)->FindClass(env, "java/util/HashMap");
if(mapClass == NULL)
{
    return NULL;
}


jsize map_len = 1;

jmethodID init = (*env)->GetMethodID(env, mapClass, "<init>", "(I)V");
jobject hashMap = (*env)->NewObject(env, mapClass, init, map_len);

jmethodID put = (*env)->GetMethodID(env, mapClass, "put",
            "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");

while( ... )
{
    jint key = ...;
    size_t sz = t->count;
    jbyteArray dd = (*env)->NewByteArray(env, sz);
    for(i = 0; i < sz; i++)
    {
        (*env)->SetByteArrayRegion(env, dd, i, 1, *data++);
    }

    (*env)->CallObjectMethod(env, hashMap, put, key, dd);

    (*env)->DeleteLocalRef(env, key);
    (*env)->DeleteLocalRef(env, dd);
}

(*env)->DeleteLocalRef(env, hashMap);
(*env)->DeleteLocalRef(env, mapClass);

答案 1 :(得分:3)

对我来说,我发现“put”方法的签名需要与上面示例中列出的签名不同。即。

jmethodID put = env->GetMethodID(mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");

答案 2 :(得分:2)

请参阅here

调用String构造函数的一些示例代码:

jstring
 MyNewString(JNIEnv *env, jchar *chars, jint len)
 {
     jclass stringClass;
     jmethodID cid;
     jcharArray elemArr;
     jstring result;

     stringClass = (*env)->FindClass(env, "java/lang/String");
     if (stringClass == NULL) {
         return NULL; /* exception thrown */
     }
 /* Get the method ID for the String(char[]) constructor */
     cid = (*env)->GetMethodID(env, stringClass,
                               "<init>", "([C)V");
     if (cid == NULL) {
         return NULL; /* exception thrown */
     }

     /* Create a char[] that holds the string characters */
     elemArr = (*env)->NewCharArray(env, len);
     if (elemArr == NULL) {
         return NULL; /* exception thrown */
     }
     (*env)->SetCharArrayRegion(env, elemArr, 0, len, chars);

     /* Construct a java.lang.String object */
     result = (*env)->NewObject(env, stringClass, cid, elemArr);

     /* Free local references */
     (*env)->DeleteLocalRef(env, elemArr);
     (*env)->DeleteLocalRef(env, stringClass);
     return result;
 }

答案 3 :(得分:2)

也可以考虑直接使用JNI的替代方案 - 例如可以为您生成JNI代码的工具。例如,JANET(免责声明:我写过它)允许您在本机方法中嵌入Java代码,因此创建和使用哈希映射就像这样简单:

... (C++ code)
`Map map = new HashMap();` // embedded Java
... (C++ code)
... const char* foo = "foo";
`map.put(#$(foo), 50);` // ["foo" -> 50]

由JANET将反向标记的语句转换为JNI代码,因此您永远不必担心签名,引用处理,异常处理等,但您仍然可以获得JNI的性能。

答案 4 :(得分:2)

以下是我对此问题的贡献,我使用了其他答案和其他地方的想法。以下是将std::map<std::string, std::string>转换为HashMap并返回的两个函数:

jobject StlStringStringMapToJavaHashMap(JNIEnv *env, 
                                        const std::map<std::string, std::string>& map);
void JavaHashMapToStlStringStringMap(JNIEnv *env, jobject hashMap, 
                                     std::map<std::string, std::string>& mapOut);

测试功能:

void TestConversions(JNIEnv *env);

提供了如何使用它的示例-btw。我已经在Android设备上运行了该测试,并且可以正常工作。

jobject StlStringStringMapToJavaHashMap(JNIEnv *env, const std::map<std::string, std::string>& map) {
  jclass mapClass = env->FindClass("java/util/HashMap");
  if(mapClass == NULL)
    return NULL;

  jmethodID init = env->GetMethodID(mapClass, "<init>", "()V");
  jobject hashMap = env->NewObject(mapClass, init);
  jmethodID put = env->GetMethodID(mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");

  std::map<std::string, std::string>::const_iterator citr = map.begin();
  for( ; citr != map.end(); ++citr) {
    jstring keyJava = env->NewStringUTF(citr->first.c_str());
    jstring valueJava = env->NewStringUTF(citr->second.c_str());

    env->CallObjectMethod(hashMap, put, keyJava, valueJava);

    env->DeleteLocalRef(keyJava);
    env->DeleteLocalRef(valueJava);
  }

  jobject hashMapGobal = static_cast<jobject>(env->NewGlobalRef(hashMap));
  env->DeleteLocalRef(hashMap);
  env->DeleteLocalRef(mapClass);

  return hashMapGobal;
}

// Based on android platform code from: /media/jni/android_media_MediaMetadataRetriever.cpp
void JavaHashMapToStlStringStringMap(JNIEnv *env, jobject hashMap, std::map<std::string, std::string>& mapOut) {
  // Get the Map's entry Set.
  jclass mapClass = env->FindClass("java/util/Map");
  if (mapClass == NULL) {
    return;
  }
  jmethodID entrySet =
    env->GetMethodID(mapClass, "entrySet", "()Ljava/util/Set;");
  if (entrySet == NULL) {
    return;
  }
  jobject set = env->CallObjectMethod(hashMap, entrySet);
  if (set == NULL) {
    return;
  }
  // Obtain an iterator over the Set
  jclass setClass = env->FindClass("java/util/Set");
  if (setClass == NULL) {
    return;
  }
  jmethodID iterator =
    env->GetMethodID(setClass, "iterator", "()Ljava/util/Iterator;");
  if (iterator == NULL) {
    return;
  }
  jobject iter = env->CallObjectMethod(set, iterator);
  if (iter == NULL) {
    return;
  }
  // Get the Iterator method IDs
  jclass iteratorClass = env->FindClass("java/util/Iterator");
  if (iteratorClass == NULL) {
    return;
  }
  jmethodID hasNext = env->GetMethodID(iteratorClass, "hasNext", "()Z");
  if (hasNext == NULL) {
    return;
  }
  jmethodID next =
    env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
  if (next == NULL) {
    return;
  }
  // Get the Entry class method IDs
  jclass entryClass = env->FindClass("java/util/Map$Entry");
  if (entryClass == NULL) {
    return;
  }
  jmethodID getKey =
    env->GetMethodID(entryClass, "getKey", "()Ljava/lang/Object;");
  if (getKey == NULL) {
    return;
  }
  jmethodID getValue =
    env->GetMethodID(entryClass, "getValue", "()Ljava/lang/Object;");
  if (getValue == NULL) {
    return;
  }
  // Iterate over the entry Set
  while (env->CallBooleanMethod(iter, hasNext)) {
    jobject entry = env->CallObjectMethod(iter, next);
    jstring key = (jstring) env->CallObjectMethod(entry, getKey);
    jstring value = (jstring) env->CallObjectMethod(entry, getValue);
    const char* keyStr = env->GetStringUTFChars(key, NULL);
    if (!keyStr) {  // Out of memory
      return;
    }
    const char* valueStr = env->GetStringUTFChars(value, NULL);
    if (!valueStr) {  // Out of memory
      env->ReleaseStringUTFChars(key, keyStr);
      return;
    }

    mapOut.insert(std::make_pair(std::string(keyStr), std::string(valueStr)));

    env->DeleteLocalRef(entry);
    env->ReleaseStringUTFChars(key, keyStr);
    env->DeleteLocalRef(key);
    env->ReleaseStringUTFChars(value, valueStr);
    env->DeleteLocalRef(value);
  }
}

void TestConversions(JNIEnv *env) {

  // Empty test
  {
    std::map<std::string, std::string> map, mapTest;
    jobject hashMap = StlStringStringMapToJavaHashMap(env, map);
    JavaHashMapToStlStringStringMap(env, hashMap, mapTest);
    assert(map == mapTest);
  }

  // One element test
  {
    std::map<std::string, std::string> map, mapTest;
    map["one"] = "uno";
    jobject hashMap = StlStringStringMapToJavaHashMap(env, map);
    JavaHashMapToStlStringStringMap(env, hashMap, mapTest);
    assert(map == mapTest);
  }

  // Two element test
  {
    std::map<std::string, std::string> map, mapTest;
    map["one"] = "uno";
    map["two"] = "duo";
    jobject hashMap = StlStringStringMapToJavaHashMap(env, map);
    JavaHashMapToStlStringStringMap(env, hashMap, mapTest);
    assert(map == mapTest);
  }

  // Huge number of elements test
  {
    std::map<std::string, std::string> map, mapTest;
    for (int n = 0; n < 10000; ++n) {
      map[std::to_string(n)] = std::to_string(n);
    }
    jobject hashMap = StlStringStringMapToJavaHashMap(env, map);
    JavaHashMapToStlStringStringMap(env, hashMap, mapTest);
    assert(map == mapTest);
  }
}