Passing RUBY Array to C DLL using Fiddle

465 views Asked by At

First I am aware that my question is similar to the one posted as the following. How to deal with array pointers in ruby Fiddle

But that question is indeed not answered. My problem is to write a function in ruby, that will accept a ruby array of float as input and return a Fiddle::Pointer that can be processed in C DLL. Here is it

# transform an ruby array of double to Fiddle::Pointer and processed as double* in C DLL
# @param [Array] array the ruby array, e.g. [1.0, 2.0, 3.0]
# @return [Fiddle::Pointer] fiddle pointer that could be processed as double * in C
def double_array_to_ptr(array)
  length = array.length
  ptr = Fiddle::Pointer.malloc(length * Fiddle::SIZEOF_DOUBLE)

  # initialize the ptr with numbers in array
  for i in 0..length-1
    # how to initialize the ptr
    # maybe ptr[start, length] would help, I have tried but no success

  end
  return ptr
end

And the C function may look like this

/**
 * \brief       H2OSetGlobalOffset set the global offset of data
 * \param[in]   H2OProjectH project project manager, this one has been initialized
 * \param[in]   double * offset offset data, the buffer is initilized in ruby 
*/
H2O_EXPORT void H2OSetGlobalOffset(H2OProjectH project, double* offset);

The function has been wrapped with Fiddle::Importer, which is the same as previous question. So the question is that how can I initialize the Fiddle::Pointer in the ruby code.

Thanks!

1

There are 1 answers

1
Jara On
arr = [1.0, 2.0, 3.0]
ptr = Fiddle::Pointer[arr.pack('E*')]

The E* is for little-endian byte order,

Got the above from this Ruby forum link

For more on packing and unpacking of different data types check this post