要将数据传递给您需要使用MemoryPointer 的函数,首先将数据从Ruby 数组复制到其中,以便在C 代码看到它时它的格式正确。使用write_array_of_* 方法之一复制一维数组的数据相当简单。对于多维数组,这有点棘手,您需要将每个数组复制到管理到MemoryPointer 的内存中的正确位置。
同样,对于函数通过指针返回的数据,您需要提供大小合适的MemoryPointer,然后将数据复制到 Ruby 数组中。同样,这对于使用 read_array_of* 方法的单维数组来说是相当容易的,而对于多维数组来说,这需要更多的工作。
这是一个简单的例子。这里我假设 C 函数的参数总是由三个三元素 int 数组组成——int[3][3]。
C 函数:
int foo(void* bar, void* baz) {
// assume both arrays are [3][3]
int(*bar_)[3] = (int (*)[3]) bar;
int(*baz_)[3] = (int (*)[3]) baz;
// Highly complex processing - double each entry.
for (int i = 0; i< 3; i++) {
for (int j = 0; j < 3; j++) {
baz_[i][j] = 2 * bar_[i][j];
}
}
return 0;
}
这是访问它的 Ruby 代码:
require 'ffi'
module MyLibrary
extend FFI::Library
ffi_lib "path/to/mylibrary.so"
# Give function a different name. You might also want to make
# it private.
attach_function(:ffi_foo, :foo, [:pointer, :pointer], :int)
# Wrap the C function with a friendly method that packages
# and unpackages the data.
def self.foo(pixels)
# Create the MemoryPointers for input and output. They are
# both 9 entry (3 * 3) arrays of uint32.
input = FFI::MemoryPointer.new(:uint32, 9)
output = FFI::MemoryPointer.new(:uint32, 9)
# Copy the input data into the input MemoryPointer
pixels.each_with_index do |ary, idx|
# The offset here is in bytes. int32 is 4 bytes, each
# array is three elements so total is 3 * 4 = 12.
input.put_array_of_int32(idx * 12, ary)
end
# Call the C function.
ffi_foo(input, output)
result = []
# Copy the data back into a Ruby array.
3.times do |idx|
result << output.get_array_of_int32(idx * 12, 3)
end
# Return the final result
result
end
end
然后你可以像这样使用它:
pixels = [[3, 34, 123], [32, 253, 34], [1, 1, 34]]
p MyLibrary.foo(pixels) #=>[[6, 68, 246], [64, 506, 68], [2, 2, 68]]
显然,您需要对其进行调整以匹配您自己函数的详细信息。您可能还应该添加错误检查,否则您可能会遇到段错误。