JNIは本当に頭痛の種になる可能性があります。あなたの機能は、表面上はうまく見えます。
まず、あなたが使用していないことに注意してくださいoffset
-それはコードの臭いです。
次に、UChar配列を解放していません。
第3に、C関数または割り当てループのいずれかが配列の境界を超えている可能性があります。
print
このような突然のクラッシュを見つけるのを助けるために、私はコンソールと組み合わせて古き良きステートメントをうまく使用しました。
まず、JNIGlobalクラスにprintlnメソッドを追加しました。
/** Print text or ASCII byte array prefixed with "JNI: ". Primarily for native code to output to the Java console. */
static public void println(Object val) {
if(val instanceof byte[]) { byte[] ba=(byte[])val; val=new String(ba,0,ba.length); }
System.out.println("JNI: "+val);
}
次に、対応するメソッドをCコードに追加しました。
void println(JNIEnv *jep, byte *format,...) {
va_list vap;
byte txt[5001];
jsize txtlen;
jclass eCls;
jint mId;
jbyteArray jText;
va_start(vap,format); vsprintf(txt,format,vap); va_end(vap);
txtlen=(long)strlen(txt);
if((eCls=(*jep)->FindClass(jep,"<your/package/here/JNIGlobal"))==0) {
printf("JNI: Global class not found (Error Text: %s)\n",txt);
return; /* give up */
}
if((mId=(*jep)->GetStaticMethodID(jep,eCls,"println","(Ljava/lang/Object;)V"))==0) {
printf("JNI: Global println method not found (Error Text: %s)\n",txt);
return; /* give up */
}
jText=(*jep)->NewByteArray(jep,txtlen);
(*jep)->SetByteArrayRegion(jep,jText,0,txtlen,(void*)txt);
(*jep)->CallStaticVoidMethod(jep,eCls,mId,jText);
}
println(env,"Some formatted output")
次に、ソースの各行を呼び出して、どこまで到達するかを確認します。私の環境(AS / 400)では、対話型実行中にJVMがクラッシュすると、コンソールが残ります。コンソールがなくなる前に出力が表示されるように、Javaコードに短い遅延を追加することをお勧めします。
だからあなたのために、そのように:
static jint testFunction(JNIEnv* env, jclass c, jobject obj,
jcharArray chsArray, int offset, int len, jcharArray dstArray) {
/**/println("** testFunction 1");
jchar* dst = env->GetCharArrayElements(dstArray, NULL);
/**/println("** testFunction 2");
if (dst != NULL) {
/**/println("** testFunction 3");
UChar *str = new UChar[len];
/**/println("** testFunction 4");
//populate str here from an ICU4C function
/**/println("** testFunction 5");
for (int i=0; i<len; i++)
dst[i] = str[i]; //this might be the problematic piece of code (can I issue an assignment like this?)
}
/**/println("** testFunction 6");
}
env->ReleaseCharArrayElements(dstArray, dst, 0);
/**/println("** testFunction 7");
}