JNI. Converting a job representing Java base objects (Boolean) to native base types (bool)

I think I managed to put most of the question in the title on this!

I am returning an object from Java to my own C ++ code:

jobject valueObject = env->CallObjectMethod(hashMapObject, hashMapGetMID, keyObject);

It is possible for me to verify that the returned object is one of the native types using something like:

jclass boolClass = env->FindClass("java/lang/Boolean");
if(env->IsInstanceOf(valueObject, boolClass) == JNI_TRUE) { }

So now I have a jobject, which, as I know, is logical (note the upper case B). The question is what is the most efficient way (given that I already have a job in my native code) to convert this to bool. Typing doesn't work, which makes sense.

Although the above example is logical, I also want to convert Character → char, Short-> short, Integer-> int, Float-> float, Double-> double.

(After I implemented it, I will post the answer to this question, which makes Boolean.booleanValue ())

+5
source share
3 answers

You have two options.

Option # 1 is what you wrote in your own answer: use the public method defined for each class to extract a primitive value.

№ 2 , : . Boolean Boolean.value. fieldID "value", . (JNI , . "" , " ".)

"" , . , , .

, jmethodID/jfieldID, ( ).

IsSameObject, IsInstanceof, "". GetObjectClass, valueObject, .

, "char". CallCharMethod (16- UTF-16) char (8- ). , char!= Jchar ( ), long!= Jlong ( 64- longs).

+5

, , . , , , JNI, , :

    if     (env->IsInstanceOf(valueObject, boolClass)           == JNI_TRUE)
    {
        jmethodID booleanValueMID   = env->GetMethodID(boolClass, "booleanValue", "()Z");
        bool booleanValue           = (bool) env->CallBooleanMethod(valueObject, booleanValueMID);
        addBoolean(key, booleanValue);
    }
    else if(env->IsInstanceOf(valueObject, charClass)           == JNI_TRUE)
    {
        jmethodID characterValueMID  = env->GetMethodID(charClass, "charValue", "()C");
        char characterValue          = (char) env->CallCharMethod(valueObject, characterValueMID);
        addChar   (key, characterValue);
    }
+1

In general, I write jni for better performance. How to achieve better performance? Using asm, primitive types and several method calls. I suggest that the design of the return type of the method can be used in c / C ++, e.g. jint, jlong, jboolean, jbyte and jchar, etc.

Calling the redundancy function and transforming will make an implementation ineffective and not implementable.

0
source

All Articles