Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNA union structure mapping

In JNA, how do you map a union structure like the following XEvent from Xlib

typedef union _XEvent {
    int type;    /* must not be changed */
    XAnyEvent xany;
    XKeyEvent xkey;
    XButtonEvent xbutton;
    XMotionEvent xmotion;
    XCrossingEvent xcrossing;
    XFocusChangeEvent xfocus;
    XExposeEvent xexpose;
    XGraphicsExposeEvent xgraphicsexpose;
    XNoExposeEvent xnoexpose;
    XVisibilityEvent xvisibility;
    XCreateWindowEvent xcreatewindow;
    XDestroyWindowEvent xdestroywindow;
    XUnmapEvent xunmap;
    XMapEvent xmap;
    XMapRequestEvent xmaprequest;
    XReparentEvent xreparent;
    XConfigureEvent xconfigure;
    XGravityEvent xgravity;
    XResizeRequestEvent xresizerequest;
    XConfigureRequestEvent xconfigurerequest;
    XCirculateEvent xcirculate;
    XCirculateRequestEvent xcirculaterequest;
    XPropertyEvent xproperty;
    XSelectionClearEvent xselectionclear;
    XSelectionRequestEvent xselectionrequest;
    XSelectionEvent xselection;
    XColormapEvent xcolormap;
    XClientMessageEvent xclient;
    XMappingEvent xmapping;
    XErrorEvent xerror;
    XKeymapEvent xkeymap;
    long pad[24];
} XEvent;

I want to be able later on to cast the XEvent in JNA to other events (like XKeyEvent, XButtonEvent, XMotionEvent ...etc) based on the type of the event received.

I am not asking for a full mapping for all the structures above. A clear explanation with a small example on how to do it will be enough.

Thanks

like image 979
Untitled Avatar asked Jan 24 '26 03:01

Untitled


1 Answers

Use the mappings defined in the JNA contrib (com.sun.jna.platform.X11) then do the following:

  1. Get the XEvent using whatever method yo prefer (e.g. XNextEvent).
  2. Determine the type of the event using the type field.
  3. Based on the type, call the method readFiled with the field name (in string) and cast the returned value to the event type of the field name.

Example:

XEvent event = new XEvent();
X11.INSTANCE.XNextEvent(display, event);
if(event.type == X11.KeyPress) {
    XKeyEvent xKey = (XKeyEvent)event.readField("xkey");
    // you can now use xKey.keycode and other fields
}
like image 82
temp Avatar answered Jan 25 '26 18:01

temp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!