I've been storing c pointers in Java through JNI by following the advice of @tulskiy in this post Passing pointers between C and Java through JNI
The trick is to cast the pointer as a jlong. So from c I have return (jlong) ptr;
I'm returning a jlong (always 64 bits) because I want my code to work on both 64 and 32 bit systems. The size in memory of a 64 bit pointer on a 64 bit computer is 64 and it follows that on a 32-bit computer, the size of the pointer in memory is 32 bits.
The problem is that on the 32 bit machine I get a compiler warning saying "casting to integer from pointer of different size." The warnings goes away if I have
return (jlong) (int32_t) ptr;
However this code is not good for the 64 bit machine.
I would like to have my code compile without warnings so that if there is a legitimate warning I will see it. Anyone have any ideas?
Thanks, Ben
A JNI global reference is a reference from "native" code to a Java object managed by the Java garbage collector. Its purpose is to prevent collection of an object that is still in use by native code, but doesn't appear to have any live references in the Java code. A JFrame is a java. awt.
Introduction to Java Native Interface: Establishing a bridge between Java and C/C++ JNI (Java Native Interface) is a foreign function interface that allows code running on JVM to call (or be called by) native applications. Using JNI, one can call methods written in C/C++ or even access assembly language.
JNI provides functions for accessing the contents of array objects. While arrays of objects must be accessed one entry at a time, arrays of primitives can be read and written directly as if they were declared in C.
There are various handy integer types in C. The one you want is probably intptr_t or uintptr_t:
return (jlong)(intptr_t) ptr;
The difference?
intptr_t
to jlong
and back is guaranteed to work provided jlong
is big enough (which you're implicitly assuming it is anyway).uinttptr_t
to jlong
and back avoids a sign-extension, but is undefined behaviour if the uintptr_t
is too big to fit in a jlong
(but all "sane" architectures/compilers just use two's complement arithmetic)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With