Subject:
[ruby-ffi] Re: FFI core concepts wiki documentation
From:
hedgehogshiatus@gmail.com
Date:
11/11/09 12:47 AM
To:
ruby-ffi@googlegroups.com



On Wed, Nov 11, 2009 at 4:10 PM, Wayne Meissner <wmeissner@gmail.com> wrote:

2009/11/11 Bryan Kearney <bkearney@redhat.com>:
Passing a Single String by Reference
-------------------------------------

Assume the method:
       int aug_get(const augeas *aug, const char *path, const char **value);

[...]
Passing an Array of Strings back by Reference
----------------------------------------------

int aug_match(const augeas *aug, const char *path, char ***matches);

Since these are pretty common things in C (well, in those types of
apis), I've been wondering if adding a higher-level wrapper would make
it easier to read/less confusing to write.

e.g.
 ref = FFI::Reference.new :string
 AugeasLib.aug_get("foo", "/bar", ref)
 str = ref.get  # returns a string, or nil for null
 # do stuff with str as you would expect

and
 ref = FFI::Reference.new :string_array # or maybe Reference.new [ :string ]

My vote would be for such a 'new' to accept (valid) vanilla Ruby:

ref = FFI::Reference.new Array.new(String.new)
str = ref.get # returns "" for nil values
and
ref = FFI::Reference.new Array.new(sz, String.new) str = ref.get # returns array of size sz, with "" for nil values
and
ref = FFI::Reference.new Array.[]('a','b','z') # returns array of size 3, with 'a','b' or 'z' for nil values

not sure if that makes sense?
Cheers

 AugeasLib.aug_match("foo", "/bar", ref)
 str_ary = ref.get  # pulls out all the strings and puts them in an
array, stopping at first null
 str_ary.each { |s| # do stuff with each string }

I think this adds a bit of clarity when reading, since it is easy to
spot that you're just passing in a reference that you expect the C
code to fill out, and not for some more generic pointer/memory use.

This could all be implemented in a third-party gem, e.g. NiceFFI,
which would be preferable to putting it in ruby-ffi itself, since that
way it can evolve faster, and be used across both CRuby and JRuby.




-- 
πόλλ' οἶδ ἀλώπηξ, ἀλλ' ἐχῖνος ἓν μέγα [The fox knows many things, but the hedgehog knows one big thing.]
 Archilochus, Greek poet (c. 680 BC – c. 645 BC)
http://wiki.hedgehogshiatus.com