[英]Is it possible that JNI function return integer or boolean?
JAVA代碼
boolean b = invokeNativeFunction();
int i = invokeNativeFunction2();
C代碼
jboolean Java_com_any_dom_Eservice_invokeNativeFunction(JNIEnv* env, jobject obj) {
bool bb = 0;
...
return // how can return 'bb' at the end of the function?
}
jint Java_com_any_dom_Eservice_invokeNativeFunction2(JNIEnv* env, jobject obj) {
int rr = 0;
...
return // how can return 'rr' at the end of the function?
}
JNI函數是否可能返回整數或布爾值? 如果是,我該怎么做?
是的,直接返回值即可。
JNIEXPORT jint JNICALL Java_com_example_demojni_Sample_intMethod(JNIEnv* env, jobject obj,
jint value) {
return value * value;
}
JNIEXPORT jboolean JNICALL Java_com_example_demojni_Sample_booleanMethod(JNIEnv* env,
jobject obj, jboolean unsignedChar) {
return !unsignedChar;
}
有Java的原始類型和原始類型,基准之間的映射關系在這里 。
我認為您的方法簽名可能是錯誤的...
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
如果您會注意以下幾點:
1)在方法周圍添加了JNIEXPORT
和JNICALL
)要返回到j<object>
類型的參數。
我認為您需要修改int示例以:
JNIEXPORT jint JNICALL Java_com_any_dom_Eservice_invokeNativeFunction2(JNIEnv* env, jobject obj) {
jint rr = 99;
...
return rr;
}
為什么不做一些靜態轉換:
return static_cast<jboolean>(bb);
return static_cast<jint>(rr);
在我的jni.h
副本中, jint
被定義為int32_t
,而jboolean
被定義為uint8_t
。 true
和false
的內部表示形式在C ++和Java(在VM級別)AFAIK中相同(即0 == false,1 == true)。
當然,您可以根據需要添加一些完整性檢查,例如:
assert(numeric_limits<jint>::is_signed == numeric_limits<decltype(rr)>::is_signed &&
numeric_limits<jint>::min() <= numeric_limits<decltype(rr)>::min() &&
numeric_limits<jint>::max() >= numeric_limits<decltype(rr)>::max());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.