Search code examples
javatypesjava-native-interfaceprimitiveautoboxing

JNI new primitive types


How can we new primitive types in JNI. I have a function that returns a jobject. It is possible to return jint, jchar, etc.

There is NewString, why not NewInteger, NewCharacter, NewDouble, etc. There is no autoboxing at JNI layer at the moment.

I can go with the NewObject call, but this will be too much overhead to create primitive types.

jobject NewInteger(JNIEnv* env, jint value)
{
    jclass cls = FindClass(env, "java/lang/Integer");
    jmethodID methodID = GetMethodID(env, cls, "<init>", "(I)V", false);
    return env->NewObject(cls, methodID, value);
}

I have wrapper functions to get Class and MethodID.


Solution

  • jint, jdouble, etc. are not jobjects. As you say, they're primitive variables. Just fill them in!

    jint someInt = 1;
    jdouble someDouble = 3.14159;
    

    Re edit: I see, you want to return boxed types like Integer, Double, etc. Yeah, the wrapper function you posted is probably the way to go.