假设这是您希望在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
ffi_lib "./my_c_lib.so"
attach_function :my_function, [:pointer, :int], :pointer
end
array = [4, 6, 4]
size = array.size
offset = 0
pointer = FFI::MemoryPointer.new :double, size
pointer.put_array_of_double offset, array
result_pointer = MyModule.my_function(pointer, size)
result_array = result_pointer.read_array_of_double(size)
p result_array
运行脚本后的结果如下:
$ ruby my_c_lib.rb
[8.0, 12.0, 8.0]
从文档中了解到,关于内存管理的注释:
https://github.com/ffi/ffi/wiki/Pointers:
FFI::MemoryPointer类使用自动垃圾回收来分配本机内存。当一个MemoryPointer超出其范围时,内存将会被释放,作为垃圾回收过程的一部分。
因此,您不需要直接调用pointer.free。另外,为了检查是否必须手动释放result_pointer,我在提取数组并打印后调用了result_pointer.free,并得到了这个警告。
warning: calling free on non allocated pointer #<FFI::Pointer address=0x007fd32b611ec0>
看起来你不需要手动释放result_pointer
。