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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With