使用Fiddle将RUBY数组传递给C DLL

时间:2016-02-04 03:56:46

标签: c ruby dll fiddle

首先我知道我的问题类似于以下发布的问题。 How to deal with array pointers in ruby Fiddle

但这个问题确实没有得到回答。我的问题是在ruby中编写一个函数,它将接受一个float的ruby数组作为输入并返回一个可以在C DLL中处理的Fiddle :: Pointer。这是它

# 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

C函数可能看起来像这样

/**
 * \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);

该函数已用Fiddle :: Importer包装,与上一个问题相同。所以问题是如何在ruby代码中初始化Fiddle :: Pointer。

谢谢!

1 个答案:

答案 0 :(得分:1)

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

E*用于小端字节顺序,

从此Ruby forum link

获得上述内容

有关打包和解包不同数据类型check this post

的更多信息