Subject:
[ruby-ffi] How to manage an Array of Structs
From:
P4010
Date:
4/27/11 11:58 AM
To:
ruby-ffi

Hi all,
I am writing an FFI interface to IP shared memory and semaphores. I
wonder if someone here can give me advice on how to manage an Array of
Structs.

I am mapping the semop() function in FFI. It has the following
signature:

#include <sys/sem.h>
int
semop(int semid, struct sembuf *sops, size_t nsops);

I wrote something like:

module Shared
  extend FFI::Library
  ffi_lib FFI::Library::LIBC

  class Sembuf < FFI::Struct
    layout :sem_num, :ushort,
      :sem_op, :short,
      :sem_flg, :short
  end

  attach_function :semop,  [:int, :pointer, :size_t], :int

end

Now the Shared#semop wants a pointer to an array of Shared::Sembuf
structs. How can I build such a pointer? I guess I should start with

op = Shared::Sembuf.new
op[:sem_num] = 0
op[:sem_op] = -1
op[:sem_flg] = 0

ops = FFI::MemoryPointer.new(Shared::Sembuf, Shared::Sembuf.size * 1)

But then I could not find how to add the op instance to the array
pointed to by ops...

I'll appreciate any suggestion...

Cheers,
-P.