1

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.

Rojj
  • 1,170
  • 1
  • 12
  • 32
  • 1
    I'm too lazy to check but you have to use `Array#pack`: `a.pack('i3')`. The object ID is not an address and even if it were the data wouldn't be in the expected format (`int[3]`). – cremno Apr 28 '16 at 05:35
  • Thanks @cremno, your comment helped me to figure it out. I should define the pointer as `Fiddle::Pointer[a.pack('i*')]` and this returns a pointer that I can then pass to the function. – Rojj Apr 29 '16 at 13:40

0 Answers0