Ruby Fiddle - Pass array to C function

368 Views Asked by At

I am trying to pass an array to a C function using Fiddle (2.0.0-p247). This is my ruby script

require 'fiddle'
clib = Fiddle.dlopen('sum_array')
f = Fiddle::Function.new(clib['sum_array'], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT],  Fiddle::TYPE_INT)
a = [1,2,3]
ptr = Fiddle::Pointer.new(a.object_id)
puts "Sum is #{f.call(ptr,3)}"

I have also tried to replace the Pointer definition with

ptr = Fiddle::Pointer.new(a.object_id, 3 * Fiddle::SIZEOF_INT)

The C function is the following:

int sum_array(int a[], int num_elements)
{
   int i, sum=0;
   for (i=0; i<num_elements; i++)
   {
     sum = sum + a[i];
   }
   return(sum);
}

When I run the script it crashes. This is the crash report.

0

There are 0 best solutions below