c - 如何处理 ruby​​ ffi gem 中的 ruby​​ 数组?

标签 c ruby ffi

我想使用 ruby​​ ffi gem 调用一个 c 函数,该函数将一个数组作为输入变量,输出是一个数组。也就是说,c 函数看起来像:

double *my_function(double array[], int size)

我创建了 ruby​​ 绑定(bind):

module MyModule
  extend FFI::Library
  ffi_lib 'c'
  ffi_lib 'my_c_lib'
  attach_function :my_function, [:pointer, int], :pointer

我想用 ruby​​ 代码调用:

result_array = MyModule.my_function([4, 6, 4], 3)

我该怎么做?

最佳答案

假设这是您希望在 ruby​​ 脚本中使用的库,将其命名为 my_c_lib.c:

#include <stdlib.h>

double *my_function(double array[], int size)
{
  int i = 0;
  double *new_array = malloc(sizeof(double) * size);
  for (i = 0; i < size; i++) {
    new_array[i] = array[i] * 2;
  }

  return new_array;
}

你可以这样编译它:

$ gcc -Wall -c my_c_lib.c -o my_c_lib.o
$ gcc -shared -o my_c_lib.so my_c_lib.o

现在,它已准备好在您的 ruby​​ 代码中使用 (my_c_lib.rb):

require 'ffi'

module MyModule
  extend FFI::Library

  # Assuming the library files are in the same directory as this script
  ffi_lib "./my_c_lib.so"

  attach_function :my_function, [:pointer, :int], :pointer
end

array = [4, 6, 4]
size = array.size
offset = 0

# Create the pointer to the array
pointer = FFI::MemoryPointer.new :double, size

# Fill the memory location with your data
pointer.put_array_of_double offset, array

# Call the function ... it returns an FFI::Pointer
result_pointer = MyModule.my_function(pointer, size)

# Get the array and put it in `result_array` for use
result_array = result_pointer.read_array_of_double(size)

# Print it out!
p result_array

这是运行脚本的结果:

$ ruby my_c_lib.rb
[8.0, 12.0, 8.0]

有关内存管理的说明...来自文档 https://github.com/ffi/ffi/wiki/Pointers :

The FFI::MemoryPointer class allocates native memory with automatic garbage collection as a sweetener. When a MemoryPointer goes out of scope, the memory is freed up as part of the garbage collection process.

因此您不必直接调用 pointer.free。此外,只是为了检查您是否必须手动释放 result_pointer,我在打印提取数组后调用了 result_pointer.free 并收到此警告

warning: calling free on non allocated pointer #<FFI::Pointer address=0x007fd32b611ec0>

所以看起来您也不必手动释放 result_pointer

关于c - 如何处理 ruby​​ ffi gem 中的 ruby​​ 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389334/

相关文章:

c - 堆的以下代码损坏是什么?

c - 重新映射堆栈成功,但随后引发 SEGV

ruby-on-rails - 推送到 Heroku 时应用程序的位置

ruby-on-rails - 格式化日期对象以显示人类可读的日期

rust - 我什么时候应该在 C 库的 Rust 绑定(bind)中使用 `&mut self` 与 `&self`?

python - 加速 cython 代码

我们可以使用数组的空指针吗

ruby - 在 Ruby 中打印包含空字段的行

perl - 在 Perl 上编写汇编

c - LuaJit FFI 从 C 函数返回字符串到 Lua?