2015-04-01 71 views
5

我想使用ruby ffi gem来调用一个具有一个数组作为输入变量并且输出是一个数组的c函数。也就是说,C函数的样子:我该如何处理ruby fm gem中的ruby数组?

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

我创建了红宝石结合为:

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) 

我如何去做这件事?

回答

4

让我们说,这是你希望在你的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 

现在,它已经准备好(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

的FFI :: MemoryPointer类分配具有自动垃圾回收作为甜味剂本机内存。当MemoryPointer超出范围时,内存将作为垃圾收集过程的一部分释放。

因此,您不应该直接致电pointer.free。此外,只是为了检查是否有手动免费result_pointer,我打印提取阵列后调用result_pointer.free,得到了这样的警告

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

所以看起来你不必手动自由result_pointer无论是。