Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Please provide a method for getting the NativeLibrary instance from Library interface #1613

Open
serinana47 opened this issue Jun 28, 2024 · 0 comments

Comments

@serinana47
Copy link

serinana47 commented Jun 28, 2024

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant