2011-01-30 104 views

回答

1

here

一些示例代碼來調用一個String構造:

jstring 
MyNewString(JNIEnv *env, jchar *chars, jint len) 
{ 
    jclass stringClass; 
    jmethodID cid; 
    jcharArray elemArr; 
    jstring result; 

    stringClass = (*env)->FindClass(env, "java/lang/String"); 
    if (stringClass == NULL) { 
     return NULL; /* exception thrown */ 
    } 
/* Get the method ID for the String(char[]) constructor */ 
    cid = (*env)->GetMethodID(env, stringClass, 
           "<init>", "([C)V"); 
    if (cid == NULL) { 
     return NULL; /* exception thrown */ 
    } 

    /* Create a char[] that holds the string characters */ 
    elemArr = (*env)->NewCharArray(env, len); 
    if (elemArr == NULL) { 
     return NULL; /* exception thrown */ 
    } 
    (*env)->SetCharArrayRegion(env, elemArr, 0, len, chars); 

    /* Construct a java.lang.String object */ 
    result = (*env)->NewObject(env, stringClass, cid, elemArr); 

    /* Free local references */ 
    (*env)->DeleteLocalRef(env, elemArr); 
    (*env)->DeleteLocalRef(env, stringClass); 
    return result; 
} 
+3

好吧!謝謝......但我如何創建一個HashMap ? – AOO 2011-01-30 18:26:28

12

這裏的代碼,你將需要修改工作

jclass mapClass = (*env)->FindClass(env, "java/util/HashMap"); 
if(mapClass == NULL) 
{ 
    return NULL; 
} 


jsize map_len = 1; 

jmethodID init = (*env)->GetMethodID(env, mapClass, "<init>", "(I)V"); 
jobject hashMap = (*env)->NewObject(env, mapClass, init, map_len); 

jmethodID put = (*env)->GetMethodID(env, mapClass, "put", 
      "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); 

while(...) 
{ 
    jint key = ...; 
    size_t sz = t->count; 
    jbyteArray dd = (*env)->NewByteArray(env, sz); 
    for(i = 0; i < sz; i++) 
    { 
     (*env)->SetByteArrayRegion(env, dd, i, 1, *data++); 
    } 

    (*env)->CallObjectMethod(env, hashMap, put, key, dd); 

    (*env)->DeleteLocalRef(env, key); 
    (*env)->DeleteLocalRef(env, dd); 
} 

(*env)->DeleteLocalRef(env, hashMap); 
(*env)->DeleteLocalRef(env, mapClass); 
+1

不應該刪除對hashMap的本地引用嗎? – miguelSantirso 2013-04-26 07:52:28

2

對我來說,我發現, 「put」方法的簽名需要與上面示例中列出的不同。即

jmethodID put = env->GetMethodID(mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); 
0

人們還可以考慮直接使用JNI的替代方案 - 例如,可以爲你生成JNI代碼的工具。例如,JANET(免責聲明:我寫的),您可以將Java代碼嵌入在你的本地方法,使創建和使用哈希地圖是如此的簡單:

... (C++ code) 
`Map map = new HashMap();` // embedded Java 
... (C++ code) 
... const char* foo = "foo"; 
`map.put(#$(foo), 50);` // ["foo" -> 50] 

背打勾語句被通過翻譯JANET轉換爲JNI代碼,因此您不必擔心簽名,引用處理,異常處理等,但您仍然可以獲得JNI的性能。