D
Daniel Berger
Hi,
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
actual code).
What should the actual code be?
module Sys
class Uptime
extend FFI::Library
attach_function :time, [ointer], :ulong
attach_function :sysctl,
[ointer, :uint, ointer, ointer, ointer, :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
end
Regards,
Dan
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
actual code).
What should the actual code be?
module Sys
class Uptime
extend FFI::Library
attach_function :time, [ointer], :ulong
attach_function :sysctl,
[ointer, :uint, ointer, ointer, ointer, :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
end
Regards,
Dan