首先我知道我的问题类似于下面发布的问题。 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。
谢谢!
arr = [1.0, 2.0, 3.0]
ptr = Fiddle::Pointer[arr.pack('E*')]
E*
用于小端字节顺序,
从这个Ruby forum link得到了上述
有关打包和拆包不同数据类型check this post的更多信息