Search code examples
javanative

Getting pointer from native syscall in Java


Having the following Java code

Object[] params = new Object[] {new Object(), null}
int ret = lib.getClass().getMethod("syscall", int.class, Object[].class).invoke(
    lib, 116, params
);

where 116 is the code (on MacOS) for gettimofday system function,

how should I specify params correctly so that I can extract timeval struct containing the result (as specified by https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/gettimeofday.2.html)


Solution

  • The function expects specific struct as a first parameter which it will populate:

    @Structure.FieldOrder({"sec", "usec"})
    public static class Timeval extends Structure {
        /**
         * Seconds.
         */
        public long sec;
    
        /**
         * Microseconds.
         */
        public long usec;
    }
    

    Supplying parameters as follows succeed the call:

    final Timeval timeval = new Timeval();
    final Object[] params = new Object[]{timeval, null};
    lib.syscall(116, params)
    

    Result can be retrieved from timeval.sec and timeval.usec.

    Thanks to @Mark Rotteveel for the hints.