I need to access a “native” C library from Java via Java Native Access (JNA). The idiomatic way to do this seems to be defining an interface that extends Library
and that declares all the functions which I need to access. Then create a singleton instance, via Native.load()
method:
public interface MyLibrary extends Library {
MyLibrary INSTANCE = Native.load("mylib", MyLibrary.class);
int some_function(int param);
}
This works fine with functions. But how do I access global variables via the JNA interface?
In the C header file it is defined like:
extern const uint16_t SOME_GLOBAL_VARIABLE;
There is little to no information available on how to access global variables via the JNA interface. The closest thing I have found is the NativeLibrary.getGlobalVariableAddress()
method. But, unfortunately, this method is in NativeLibrary
class, not in the Library
interface!
And there also seems to be no way to get a NativeLibrary
instance when working with a custom interface (derived from the Library
interface) and with the Native.load()
method. I probably could use NativeLibrary.loadLibrary()
instead, in order to get a NativeLibrary
instance and be able to use getGlobalVariableAddress()
, but then, how do I apply my interface to that in order to invoke the functions? In other words, is there any way in JNA to go from Library
to NativeLibrary
or vice versa?
Coronado Quiñones is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.