如何在以结构为参数的Ruby FFI方法中包装函数?
我试图使用ruby-ffi从共享对象调用函数。 我将以下内容编译成共享对象:
#include typedef struct _WHAT { int d; void * something; } WHAT; int doit(WHAT w) { printf("%d\n", wd); return wd; }
问题是,如何在Ruby中使用attach_function
声明函数? 如何在Ruby中的参数列表中定义struct参数(WHAT w)? 它不是:指针,并且似乎不适合ruby-ffi文档中描述的任何其他可用类型,那么它会是什么?
根据您的情况,检查如何在https://github.com/ffi/ffi/wiki/Structs中 使用Structs :
class What < FFI::Struct layout :d, :int, :something, :pointer end
现在附加函数 ,参数,因为你通过值传递struct ,将是What.by_value
(用你上面命名的struct class替换What):
attach_function 'doit', [What.by_value],:int
现在如何调用该函数 :
mywhat = DoitLib::What.new mywhat[:d] = 1234 DoitLib.doit(mywhat)
现在完整的文件:
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)