Java – convert a C long type to JNI jlong

I use JNI to transfer data between C and Java I need to pass a "long" type and use something like this:

long myLongVal = 100;
 jlong val = (jlong)myLongVal;
 CallStaticVoidMethod(myClass,"(J)V",(jvalue*)val);

However, in Java, when the 'long' parameter is retrieved, it is retrieved as a very large negative number What on earth did I do wrong?

Solution

When you pass a jlong (which is 64 bits) as a pointer (which is likely to be 32 bits), you are bound to lose data I don't know what the Convention is, but try this:

CallStaticVoidMethodA(myClass,(jvalue*)&val); //Note address-of!

Or this:

CallStaticVoidMethod(myClass,val);

It is... The method of jvalue array, and the no postfix method equates C with scalar Java type

The first clip is a little unsafe; A better, if more lengthy, alternative is:

jvalue jv;
jv.j = val;
CallStaticVoidMethodA(myClass,&jv);

In some unusual CPU architectures, the alignment requirements of jlong variables and jvalue unions may be different When you explicitly declare a union, the compiler takes care of it

Note also that the C long data type is usually 32 bits Jlong is 64 bit. On 32-bit platforms, the non-standard C equivalent is long or long__ int64.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>