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

Dav*_*vid 6 c java java-native-interface hashmap

我有Object一个HashMap领域.当Object传递给C时,我该如何访问该字段?

ObjectClass具有以下字段:

private String hello;
private Map<String, String> params = new HashMap<String, String>();
Run Code Online (Sandbox Code Playgroud)

Jos*_*hDM 12

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

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

容器对象:

public class Container {

    private String hello;
    private Map<String, String> parameterMap = new HashMap<String, String>();

    public Map<String, String> getParameterMap() {
        return parameterMap;
    }
}
Run Code Online (Sandbox Code Playgroud)

将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);
}
Run Code Online (Sandbox Code Playgroud)

相关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.
}
Run Code Online (Sandbox Code Playgroud)

值得注意的是,我并没有为在方法本身中初始化methodIDs和类而烦恼.这个SO答案向您展示如何缓存它们以便重复使用.