New primitive JNI types

How can we use the new primitive types in JNI. I have a function that returns a jobject . You can return jint , jchar , etc.

There is a NewString , why not NewInteger , NewCharacter , NewDouble , etc. At the moment, there is no autoboxing at the JNI level.

I can go with a call to NewObject , but for creating primitive types this would be too much overhead.

 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.

+4
source share
2 answers

jint , jdouble , etc. not jobjects . As you say, these are primitive variables. Just fill them out!

 jint someInt = 1; jdouble someDouble = 3.14159; 

Re edit: I see you want to return types in a box, such as Integer , Double , etc. Yes, you are probably the posting method you posted is the way to go.

+7
source

Why do you feel that this approach is β€œtoo much overhead”? If you want to return a value in a box (which is an object containing a primitive, not a "primitive type"), you need to create this object.

One option is to call the valueOf() method on a shell type.

However, I think that you'd better return the actual primitive value and let it get the box (if you need it) after it is on the Java side.


If you are worried about the overhead of finding a function / constructor, you should cache the method identifiers. Unlike object pointers, they won't change (with some caveats that unload classes that don't apply to primitive wrappers). See Clause 10.7 here: http://java.sun.com/docs/books/jni/html/pitfalls.html

+1
source

Source: https://habr.com/ru/post/1304809/


All Articles