Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap function in Ruby FFI method that takes struct as argument?

Tags:

ruby

ffi

I am trying to call a function from a shared object using ruby-ffi. I compiled the following into a shared object:

#include <stdio.h>

typedef struct _WHAT {
  int d;
  void * something;
} WHAT;

int doit(WHAT w) {
  printf("%d\n", w.d);
  return w.d;
}

The problem is, how do I declare the function with attach_function in Ruby? How is the struct argument (WHAT w) defined in the list of arguments in Ruby? It is not a :pointer, and does not seem to fit any of the other available types described in the ruby-ffi documentation, so what would it be?

like image 861
mydoghasworms Avatar asked Jan 18 '23 17:01

mydoghasworms


1 Answers

Check how to use Structs in https://github.com/ffi/ffi/wiki/Structs, for your case:

class What < FFI::Struct
  layout :d, :int,
         :something, :pointer
end

Now attach the function, the argument, since you are passing the struct by value, is going to be What.by_value(replacing What by whatever you have named you struct class above):

attach_function 'doit', [What.by_value],:int

And now how to call the function:

mywhat = DoitLib::What.new
mywhat[:d] = 1234
DoitLib.doit(mywhat)

And now the complete file:

require 'ffi'

module DoitLib
  extend FFI::Library
  ffi_lib "path/to/yourlibrary.so"

  class What < FFI::Struct
    layout :d, :int,
           :something, :pointer
  end

  attach_function 'doit', [What.by_value],:int

end

mywhat = DoitLib::What.new
mywhat[:d] = 1234
DoitLib.doit(mywhat)
like image 169
Jorge Núñez Avatar answered Jan 20 '23 05:01

Jorge Núñez