kburkhardt
kburkhardt

Reputation: 153

How to use ruby FFI to read array of static structures

I have a static array of structures in C that I'd like to read in Ruby.

The C data structure is like this:

typedef struct myStruct {
  char *name;
  int val;

} myStruct;

myStruct myData[] = {
 {"First", 0},
 {"Second", 1},
 {"Third", 2}
};

How can I read the myData array from Ruby using FFI and attach_variable?

I have this ruby code:

module MyLib

  class MyStruct < FFI:Struct
    layout :name, :string,
           :val, :int
  end

  attach_variable :myData, :myData, :pointer


  def self.readDataArray
    pointer = myData
    ??? how to use this with MyStruct to iterate through the array ???
  end
end

Upvotes: 2

Views: 628

Answers (1)

PJK
PJK

Reputation: 2112

There's no particularly nice way, I'm afraid. read_array_of_type doesn't work for structs.

You can achieve this using simple pointer arithmetics:

def self.readDataArray
    pointer = myData
    array_of_structs = 3.times.map { |idx| 
        MyStruct.new(pointer + idx * MyStruct.size)
    }
    # Do your business
end

Upvotes: 2

Related Questions