2015-04-01 22 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無論是。