XGetInputFocus 的正确 JNA 映射是什么

What is the correct JNA mapping for XGetInputFocus

我正在尝试通过 JNA 映射 X11 XGetInputFocus。原始方法签名是

XGetInputFocus(Display *display, Window *focus_return, int *revert_to_return)

我假设可以使用已经定义的 JNA 平台类型映射到 Java 中的以下内容。

void XGetInputFocus(Display display, Window focus_return, IntByReference revert_to_return);

这与 documentation 中描述的建议相关。我现在使用以下代码调用它

final X11 XLIB = X11.INSTANCE;
Window current = new Window();
Display display = XLIB.XOpenDisplay(null);
if (display != null) {
   IntByReference revert_to_return = new IntByReference();
   XLIB.XGetInputFocus(display, current, revert_to_return);
}

但是,它使 JVM 崩溃

# Problematic frame:
# C  [libX11.so.6+0x285b7]  XGetInputFocus+0x57

我错过了什么?

在原生 X11 函数中

XGetInputFocus(Display *display, Window *focus_return, int *revert_to_return)

参数Window *focus_return用于return一个Window。 JNA 实现 Window 非常像一个不可变类型, 因为在C语言中它是由typedef XID Window;定义的。 因此,C 中的类型 Window* 需要映射到 JNA 中的 WindowByReference
(这与 C 中的 int* 需要映射的原因基本相同 到 JNA 中的 IntByReference。)

那么扩展的X11界面可以是这样的:

public interface X11Extended extends X11 {
    X11Extended INSTANCE = (X11Extended) Native.loadLibrary("X11", X11Extended.class);

    void XGetInputFocus(Display display, WindowByReference focus_return, IntByReference revert_to_return);
}

并且您的代码应该进行相应的修改:

X11Extended xlib = X11Extended.INSTANCE;
WindowByReference current_ref = new WindowByReference();
Display display = xlib.XOpenDisplay(null);
if (display != null) {
    IntByReference revert_to_return = new IntByReference();
    xlib.XGetInputFocus(display, current_ref, revert_to_return);
    Window current = current_ref.getValue();
    System.out.println(current);
}

现在程序不再崩溃了。 对我来说它打印 0x3c00605.