我有一个 Object
,它有一个 HashMap
字段。当 Object
传递给 C 时,我如何访问该字段?
Object
的Class
具有以下字段:
private String hello;
private Map<String, String> params = new HashMap<String, String>();
最佳答案
您问题的答案实际上归结为为什么您要传递一个 Map
到 C 而不是迭代你的 Map
在 Java 中并将内容传递给 C。但是,我有什么资格质疑为什么?
你问如何访问HashMap
(在您提供的代码中,Map
)字段?用 Java 为它编写一个访问器方法,并在传递容器时从 C 调用该访问器方法 Object
.下面是一些简单的示例代码,展示了如何传递 Map
从 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;
}
}
将容器传递给 JNI 的主类:
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.
}
值得注意的是,我并不热衷于在方法本身中初始化方法 ID 和类; this SO Answer向您展示如何缓存它们以供重复使用。
关于java - 如何通过 JNI 将 HashMap 从 Java 发送到 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16850204/