我正在尝试使用 FFI 实现 Darknet library 中的一些功能。 :
require 'ffi'
class Image < FFI::Struct
layout :w, :int
layout :h, :int
layout :c, :int
layout :data, :pointer
end
class Darknet
extend FFI::Library
ffi_lib "./libdarknet.so"
attach_function :load_image_color, [:string, :int, :int], Image
end
image = Darknet.load_image_color("./test.jpg", 0, 0)
文件名字符串似乎没有通过:
Cannot load image "(null)"
STB Reason: can't fopen
这里是the function和 the declaration .
我对 FFI 还很陌生,但我已经成功地实现了其他功能,没有任何问题。如果有人能给我指点(没有双关语),我一定错过了一些明显的东西......
最佳答案
Ruby 字符串与 C char *
(或 char []
)不同,后者以 null 结尾(最后一个字符是 ASCII 0 - '\0'
) 连续的字符数组,通常被认为是 c 中的“字符串”。
因此,您需要通过宏 StringValueCStr(str)
将 ruby 字符串转换为指针(其中 str
是字符串变量 ”。/test.jpg"
)。还有 StringValuePtr(str)
选项,它在性能方面更好,但它并不完全安全,因为它没有考虑到以下事实: c 字符串以 null 终止,因此字符串中不能有 null 终止符(Ruby 字符串允许)。另一方面,StringValueCStr()
确实考虑到了这一点,因此确保您拥有有效的 C 字符串。
关于c - ruby /FFI : String not getting to *char function argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50917280/