我有一個Object
,它有一個HashMap
字段。當Object
傳遞給C時,如何訪問該字段?如何通過JNI發送從Java到H的HashMap
的Object
的Class
具有以下字段:
private String hello;
private Map<String, String> params = new HashMap<String, String>();
我有一個Object
,它有一個HashMap
字段。當Object
傳遞給C時,如何訪問該字段?如何通過JNI發送從Java到H的HashMap
的Object
的Class
具有以下字段:
private String hello;
private Map<String, String> params = new HashMap<String, String>();
回答你的問題實際上可以歸結爲爲什麼你想傳遞一個Map
到C,而不是在Java中遍歷您Map
並將內容傳遞給C.但是,我是誰來質疑爲什麼?
您問如何訪問HashMap
(在您提供的代碼中,Map
)字段?使用Java編寫訪問器方法,並在通過容器Object
時從C調用訪問器方法。下面是一些簡單的示例代碼,展示瞭如何將Map
從Java傳遞到C以及如何訪問Map
的size()
方法。從它,你應該能夠推斷如何調用其他方法。
容器對象:
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向您展示瞭如何緩存它們以供重複使用。
基本上,你會像其他任何物體一樣傳遞它。但要從C訪問它,您需要調用該類的Java方法。 –