Say this is the library you want to use in a ruby script, call it 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; }
You can compile it like this:
$ gcc -Wall -c my_c_lib.c -o my_c_lib.o $ gcc -shared -o my_c_lib.so my_c_lib.o
Now it is ready for use in your ruby code ( my_c_lib.rb ):
require 'ffi' module MyModule extend FFI::Library
And here is the result of running the script:
$ ruby my_c_lib.rb [8.0, 12.0, 8.0]
A note on memory management ... from the docs https://github.com/ffi/ffi/wiki/Pointers :
The FFI :: MemoryPointer class allocates internal memory with automatic garbage collection as a sweetener. When MemoryPointer goes out of scope, memory is freed as part of the garbage collection process.
Therefore, you do not need to directly call pointer.free . Also, just to check if you need to manually free result_pointer , I called result_pointer.free after printing the array extraction and got this warning
warning: calling free on non allocated pointer
So it seems you do not need to manually release result_pointer .
Sandy
source share