Hi,
I’ve recently been trying to port some C code over to FFI. I’m trying
to figure out how to unravel the gr_mem group struct member. Any
suggestions?
require ‘ffi’
module Sys
class Admin
extend FFI::Library
class GroupStruct < FFI::Struct
layout(
:gr_name, :string,
:gr_passwd, :string,
:gr_gid, :int,
:gr_mem, :pointer
)
end
attach_function :getgrgid, [:int], :pointer
def self.get_group(gid)
GroupStruct.new(getgrgid(gid))
end
end
end
How do I unravel the gr_mem struct member?
struct = Sys::Admin.get_group(84)
p struct[:gr_mem]
Regards,
Dan
2009/8/2 Daniel B. [email protected]:
def self.get_group(gid)
GroupStruct.new(getgrgid(gid))
end
[…]
How do I unravel the gr_mem struct member?
struct = Sys::Admin.get_group(84)
p struct[:gr_mem]
Hello,
the gr_mem member of the group structure is a NULL terminated array of
zero terminated strings, so you need to read all the string pointers
from the array until you encounter a null pointer and then read the
string data from each string pointer.
I would suggest the use of an auxiliary method, which could actually
be added to the FFI::Pointer class for convenience:
class FFI::Pointer
def read_string_array_to_null()
elements = []
psz = self.class.size
loc = self
until ((element = loc.read_pointer).null?)
elements << element.read_string_to_null
loc += psz
end
elements
end
end
Using this method, you can unravel the mysterious pointer member as
follows:
p struct[:gr_mem].read_string_array_to_null
I hope that helps,
Thomas
On Aug 2, 6:13 am, Thomas C. [email protected] wrote:
end
class FFI::Pointer
elements
Thomas
Thank you for that Thomas, it worked great.
I also found nice-ffi, and I suspect it may have some convenient way
of doing what you’re doing there, only I don’t see it.
Regards,
Dan