zyl1024 zyl1024 - 1 year ago 196
Java Question

JNA library and native library not found error

I want to use JNA to detect foreground application on Linux (Ubuntu 14). I followed this link
Find out what application (window) is in focus in Java
but I got the following error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'XLib': Native library (linux-x86-64/libXLib.so) not found in resource path ([file:/home/zzhou/workspace/home_prioritization_plus/bin/, file:/home/zzhou/Downloads/jna-4.1.0.jar, file:/home/zzhou/Downloads/jna-platform-4.1.0.jar])
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:271)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:398)
at com.sun.jna.Library$Handler.<init>(Library.java:147)
at com.sun.jna.Native.loadLibrary(Native.java:412)
at com.sun.jna.Native.loadLibrary(Native.java:391)
at FunctionalityTest$XLib.<clinit>(FunctionalityTest.java:15)
at FunctionalityTest.main(FunctionalityTest.java:23)

The code is:

import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.platform.unix.X11;
import com.sun.jna.win32.StdCallLibrary;

public class FunctionalityTest {

static class Psapi {
static { Native.register("psapi"); }
public static native int GetModuleBaseNameW(Pointer hProcess, Pointer hmodule, char[] lpBaseName, int size);

public interface XLib extends StdCallLibrary {
XLib INSTANCE = (XLib) Native.loadLibrary("XLib", Psapi.class); // <-- PROBLEM

int XGetInputFocus(X11.Display display, X11.Window focus_return, Pointer revert_to_return);

public static void main(String args[]) {
if(Platform.isLinux()) { // Possibly most of the Unix systems will work here too, e.g. FreeBSD
final X11 x11 = X11.INSTANCE;
final XLib xlib= XLib.INSTANCE;
X11.Display display = x11.XOpenDisplay(null);
X11.Window window=new X11.Window();
xlib.XGetInputFocus(display, window,Pointer.NULL);
X11.XTextProperty name=new X11.XTextProperty();
x11.XGetWMName(display, window, name);


To import JNA library, I downloaded jna and jna-platform from https://github.com/twall/jna and use Configure Build Path... in Eclipse to add library. I did not install anything. May that be the source of the problem?

Thanks for your help.

Answer Source

Afaik, even for JNA, you have to load the library in Java in order for JNA to find it. (tested for win32, not linux)

Try this just above Native.loadLibrary:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download