如何在以struct作为参数的Ruby FFI方法中包装函数? [英] How to wrap function in Ruby FFI method that takes struct as argument?
问题描述
我正在尝试使用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;
}
问题是,如何在Ruby中使用attach_function
声明函数?在Ruby的参数列表中如何定义struct参数(w w)?它不是:pointer,并且似乎不适合ruby-ffi文档中描述的任何其他可用类型,那么它将是什么呢?
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
现在附加函数,由于您要通过值传递结构,因此参数将变为What.by_value
(用您命名的内容替换What)上面的struct类):
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
现在如何调用函数:
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)
这篇关于如何在以struct作为参数的Ruby FFI方法中包装函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!