How to use ruby FFI to read array of static structures -


i have static array of structures in c i'd read in ruby.

the c data structure this:

typedef struct mystruct {   char *name;   int val;  } mystruct;  mystruct mydata[] = {  {"first", 0},  {"second", 1},  {"third", 2} }; 

how can read mydata array ruby using ffi , attach_variable?

i have 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 use mystruct iterate through array ???   end end 

there's no particularly nice way, i'm afraid. read_array_of_type doesn't work structs.

you can achieve using simple pointer arithmetics:

def self.readdataarray     pointer = mydata     array_of_structs = 3.times.map { |idx|          mystruct.new(pointer + idx * mystruct.size)     }     # business end 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -