Question

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.

Was it helpful?

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.

OTHER TIPS

Why do you feel that this approach is "too much overhead"? If you want to return a boxed value (which is an object that holds a primitive, not a "primitive type") then you need to create that object.

One alternative is to call the valueOf() method on the wrapper type.

However, I think you're better off returning the actual primitive value, and letting it get boxed (if you need that) once it's on the Java side.


If you're worried about the overhead for the function/constructor lookup, then you should cache the method IDs. Unlike object pointers, they will not change (with some caveats re unloaded classes that don't apply to primitive wrappers). See item 10.7 here: http://java.sun.com/docs/books/jni/html/pitfalls.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top