gpt4 book ai didi

ruby - 如何在以结构为参数的 Ruby FFI 方法中包装函数?

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:00 27 4
gpt4 key购买 nike

我正在尝试使用 ruby​​-ffi 从共享对象调用函数。我将以下内容编译成一个共享对象:

#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 的参数列表中的结构参数(WHAT w)是如何定义的?它不是 :pointer,而且似乎不适合 ruby​​-ffi 文档中描述的任何其他可用类型,那么它会是什么?

最佳答案

检查如何使用结构 https://github.com/ffi/ffi/wiki/Structs ,对于你的情况:

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

现在附加函数,因为您按值传递结构,参数将是What.by_value(替换无论你在上面命名为 struct class 是什么):

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)

关于ruby - 如何在以结构为参数的 Ruby FFI 方法中包装函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8982393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com