c - How do I handle ruby arrays in ruby ffi gem? -


i want use ruby ffi gem call c function has array input variable , output array. is, c function looks like:

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

i have created ruby binding as:

module mymodule   extend ffi::library   ffi_lib 'c'   ffi_lib 'my_c_lib'   attach_function :my_function, [:pointer, int], :pointer 

i make call in ruby code like:

result_array = mymodule.my_function([4, 6, 4], 3) 

how go this?

let's library wish use in ruby script, call my_c_lib.c:

#include <stdlib.h>  double *my_function(double array[], int size) {   int = 0;   double *new_array = malloc(sizeof(double) * size);   (i = 0; < size; i++) {     new_array[i] = array[i] * 2;   }    return new_array; } 

you can compile so:

$ 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's ready use in in ruby code (my_c_lib.rb):

require 'ffi'  module mymodule   extend ffi::library    # assuming library files in same directory 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 pointer array pointer = ffi::memorypointer.new :double, size  # fill memory location data pointer.put_array_of_double offset, array  # call function ... returns ffi::pointer result_pointer = mymodule.my_function(pointer, size)  # array , put in `result_array` use result_array = result_pointer.read_array_of_double(size)  # print out! p result_array 

and here result of running script:

$ ruby my_c_lib.rb [8.0, 12.0, 8.0] 

a note on memory management...from docs https://github.com/ffi/ffi/wiki/pointers:

the ffi::memorypointer class allocates native memory automatic garbage collection sweetener. when memorypointer goes out of scope, memory freed part of garbage collection process.

so shouldn't have call pointer.free directly. also, check whether had manually free result_pointer, called result_pointer.free after printing extracting array , got warning

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

so looks don't have manually free result_pointer either.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -