如何通过JNI将HashMap从Java发送到C.

我有一个具有HashMap字段的Object 。 当Object传递给C时,如何访问该字段?

ObjectClass包含以下字段:

 private String hello; private Map params = new HashMap(); 

您的问题的答案实际上归结为您为什么要将Map传递给C而不是在Java中迭代Map并将内容传递给C.但是,我是谁来质疑为什么?

您问如何访问HashMap (在您提供的代码, Map )字段? 在Java中为它编写一个访问器方法,并在传递容器Object时从C调用该访问器方法。 下面是一些简单的示例代码,展示了如何将Map从Java传递到C,以及如何访问Mapsize()方法。 从中,您应该能够推断出如何调用其他方法。

容器对象:

 public class Container { private String hello; private Map parameterMap = new HashMap(); public Map getParameterMap() { return parameterMap; } } 

将Container传递给JNI的Master Class:

 public class MyClazz { public doProcess() { Container container = new Container(); container.getParameterMap().put("foo","bar"); manipulateMap(container); } public native void manipulateMap(Container container); } 

相关C函数:

 JNIEXPORT jint JNICALL Java_MyClazz_manipulateMap(JNIEnv *env, jobject selfReference, jobject jContainer) { // initialize the Container class jclass c_Container = (*env)->GetObjectClass(env, jContainer); // initialize the Get Parameter Map method of the Container class jmethodID m_GetParameterMap = (*env)->GetMethodID(env, c_Container, "getParameterMap", "()Ljava/util/Map;"); // call said method to store the parameter map in jParameterMap jobject jParameterMap = (*env)->CallObjectMethod(env, jContainer, m_GetParameterMap); // initialize the Map interface jclass c_Map = env->FindClass("java/util/Map"); // initialize the Get Size method of Map jmethodID m_GetSize = (*env)->GetMethodID(env, c_Map, "size", "()I"); // Get the Size and store it in jSize; the value of jSize should be 1 int jSize = (*env)->CallIntMethod(env, jParameterMap, m_GetSize); // define other methods you need here. } 

值得注意的是,我并不是在为方法本身初始化methodIDs和类而疯狂; 这个SO答案向您展示如何缓存它们以便重复使用。