- Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
As the title says, please provide a method for getting the NativeLibrary instance from a Library interface instance!
Background
The idiomatic way of using JNA is like this:
public interface SomeLibrary extends Library { SomeLibrary INSTANCE = Native.load("libfoo", SomeLibrary.class); int some_function(int param); }public class MainClass { public static void main(String[] args){ SomeLibrary.INSTANCE.some_function(42); } }But how do we access global variables from here?
TTBOMK, we must use the NativeLibrary.getGlobalVariableAddress() method. But how to get the NativeLibrary instance from the Library interface instance? Currently, it appears that there is no way to do this – except by manually using getInvocationHandler() from java.lang.reflect.Proxy to get the Handler instance out of the Library interface, and then call getNativeLibrary() on it. This is not trivial to figure out at all. I was only able to figure it out with some help from another user on StackOverflow. Also, even if you know that java.lang.reflect.Proxy must be used, doing this is unnecessarily cumbersome 😩
BTW: Loading the library for a second time, via NativeLibrary.getInstance() method, does not seem like a good solution.
Request
Please see my PR here:
#1612
Usage Example
public interface SomeLibrary extends Library { SomeLibrary INSTANCE = Native.load("libfoo", SomeLibrary.class); static class NativeLibraryHolder { public static final NativeLibrary LIBRARY = Library.getNativeLibrary(INSTANCE); // <-- this is new !!! } static class SOME_GLOBAL_VARIABLE { private static final Pointer ADDRESS = NativeLibraryHolder.LIBRARY.getGlobalVariableAddress("FOOBAR"); int get() { return ADDRESS.getInt(0L); } void set(final int newValue) { ADDRESS.setInt(0L, newValue); } } int some_function(int param); }