問題描述
我有一個 Object
有一個 HashMap
字段.當 Object
傳遞給 C 時,如何訪問該字段?
I have an Object
that has a HashMap
field. When the Object
is passed to C, how can I access the field?
Object
的Class
有以下字段:
private String hello;
private Map<String, String> params = new HashMap<String, String>();
推薦答案
你的問題的答案真的歸結為為什么你想將 Map
傳遞給C 而不是在 Java 中迭代您的 Map
并將內容傳遞給 C.但是,我該質疑為什么?
The answer to your question really boils down to why you'd want to pass a Map
to C rather than iterate your Map
in Java and pass the contents to C. But, who am I to question why?
您問如何訪問 HashMap
(在您提供的代碼中,Map
)字段?在 Java 中為其編寫訪問器方法,并在傳遞容器 Object
時從 C 中調用該訪問器方法.下面是一些簡單的示例代碼,展示了如何將 Map
從 Java 傳遞到 C,以及如何訪問 Map的
size()
方法代碼>.從中,您應該能夠推斷出如何調用其他方法.
You ask how to access the HashMap
(in your provided code, Map
) field? Write an accessor method for it in Java and call that accessor method from C when you pass the container Object
. Below is some bare-bones sample code showing how to pass a Map
from Java to C, and how to access the size()
method of the Map
. From it, you should be able to extrapolate how to call other methods.
容器對象:
public class Container {
private String hello;
private Map<String, String> parameterMap = new HashMap<String, String>();
public Map<String, String> getParameterMap() {
return parameterMap;
}
}
將容器傳遞給 JNI 的主類:
Master Class which passes a Container to JNI:
public class MyClazz {
public doProcess() {
Container container = new Container();
container.getParameterMap().put("foo","bar");
manipulateMap(container);
}
public native void manipulateMap(Container container);
}
相關C函數(shù):
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.
}
值得注意的是,我并不熱衷于在方法本身中初始化 methodID 和類;this SO Answer 向您展示了如何緩存它們以供重復使用.
Of note, I'm not crazy about initializing methodIDs and classes in the method itself; this SO Answer shows you how to cache them for re-use.
這篇關于如何通過 JNI 將 HashMap 從 Java 發(fā)送到 C的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!