2013-05-31 28 views
3

我有一個Object,它有一個HashMap字段。當Object傳遞給C時,如何訪問該字段?如何通過JNI發送從Java到H的HashMap

ObjectClass具有以下字段:

private String hello; 
private Map<String, String> params = new HashMap<String, String>(); 
+1

基本上,你會像其他任何物體一樣傳遞它。但要從C訪問它,您需要調用該類的Java方法。 –

回答

10

回答你的問題實際上可以歸結爲爲什麼你想傳遞一個Map到C,而不是在Java中遍歷您Map並將內容傳遞給C.但是,我是誰來質疑爲什麼?

您問如何訪問HashMap(在您提供的代碼中,Map)字段?使用Java編寫訪問器方法,並在通過容器Object時從C調用訪問器方法。下面是一些簡單的示例代碼,展示瞭如何將Map從Java傳遞到C以及如何訪問Mapsize()方法。從它,你應該能夠推斷如何調用其他方法。

容器對象:

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向您展示瞭如何緩存它們以供重複使用。

+0

是的,我已經找到了從Java到C的所有複雜對象轉換的通用解決方案,非常感謝:-) – David

+0

從JNI調用hashmap方法效率不高嗎?我想從Java傳遞一個屬性對象到JNI層。一個想法是從JNI直接調用屬性對象的方法,另一個想法是將屬性Map轉換爲java層中的鍵和值數組,並將數組傳遞給JNI本地方法。哪一個是有效的?還是有其他方法可以考慮? – Sandy