Subject:
[ruby-ffi] Re: Turning a Struct into its binary representation
From:
candlerb
Date:
5/8/11 4:41 AM
To:
ruby-ffi

> > (2) Suppose I want to create a packed structure which is a contiguous
> > array of Foos. I found an example for InlineArrayOfStructs, but not
> > how to make an array of structs at the top level.
>
> Have a read of:
>
> https://groups.google.com/d/msg/ruby-ffi/2JxDNdXlcTc/GP2gbjtatqAJ
>
> If you can figure it out from that thread, *please* add a wiki page on it.

Hmm. I think it's saying that if you want an array of structs, then
you first build the array as a piece of contiguous memory, then you
can wrap each member in a separate struct object. Something like this:

   n_foos = 2
   m = FFI::MemoryPointer.new(Foo, n_foos)
   farr = n_objs.times.collect do |i|
     Foo.new(m + i * Foo.size)
   end

So now I have an array of Foo objects, each of which references the
relevant part of the underlying storage. That's doing it the opposite
way to how I was before (creating an array of Foo objects first, then
copying them). But it makes sense.

> One obvious use where FFI::Buffer is a clear win, is for small, single-use
> native memory areas (e.g. the 'length' pointer in getsockopt).  It is up to
> an order of magnitude (10x) faster to use a FFI::Buffer which gets copied
> to/from native memory for that single use, than it is to use a
> FFI::MemoryPointer and handle the allocation/release management overhead.

And how does it compare if you pass a native String? Does this just
get wrapped in an FFI::Buffer?