I’m trying to get better at FFI, but I’m getting stumped on how to
create and pass pointers to functions.
In the example below, in the Sys::Uptime.seconds method, I’m trying to
figure out how to create and pass a pointer for the mib (a 2-element
integer array) and the timeval size (i.e. where I have a ‘?’ instead of
What should the actual code be?
attach_function :time, [:pointer], :ulong attach_function :sysctl, [:pointer, :uint, :pointer, :pointer, :pointer, :uint], :int CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end # How do I create the mib? How do I pass the address of tv.size? def self.seconds tv = Timeval.new mib = [CTL_KERN, KERN_BOOTTIME] # What's the proper way to call this? if sysctl(?, 2, tv, ?, nil, 0) != 0 raise SystemCallError, 'sysctl()' end time(nil) - tv[:tv_sec] end end