I am using JNI to pass data between C++ and Java. I need to pass a ‘long’ type, and am doing so using something like:
long myLongVal = 100;
jlong val = (jlong)myLongVal;
CallStaticVoidMethod(myClass, "(J)V", (jvalue*)val);
However in Java, when the ‘long’ parameter is retrieved, it gets retrieved as some very large negative number. What am I doing wrong?
When you pass a jlong (which is 64 bit) as a pointer (which is, most likely, 32-bit) you necessarily lose data. I’m not sure what’s the convention, but try either this:
or this:
It’s
...Amethods that take a jvalue array, the no-postfix methods take C equivalents to scalar Java types.The first snippet is somewhat unsafe; a better, if more verbose, alternative would be:
On some exotic CPU archtectures, the alignment requirements for
jlongvariables andjvalueunions might be different. When you declare a union explicitly, the compiler takes care of that.Also note that C++
longdatatype is often 32-bit. jlong is 64 bits, on 32-bit platforms the nonstandard C equivalent islong longor__int64.