如何在以 struct 作为参数的 Ruby FFI 方法中包装函数?

发布于 2024-12-28 17:49:21 字数 374 浏览 0 评论 0原文

我正在尝试使用 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 文档中描述的任何其他可用类型,那么它会是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请止步禁区 2025-01-04 17:49:21

https://github.com/ffi/ 中查看如何使用 Structs ffi/wiki/Structs,对于您的情况:

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

现在附加函数,参数,因为您按值传递结构,将是What.by_value(用上面您命名的结构类替换 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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文