我目前正在开发 C 字符串度量库,并正在为 ruby 编写绑定(bind)。使用ffi如何附加带有诸如 char *function(const char *, const char *)
之类的签名的函数?相关函数将使用 malloc 在堆上分配一个字符串,然后返回指向该字符串的指针。
我相信我需要将 ffi 附加函数包装在 ruby 方法中,以便我可以将返回的字符串指针转换为 ruby 字符串并释放旧指针。
最佳答案
经过一番工作并在 irb
中搞乱之后,我弄清楚了如何安全地包装返回 char *
的 C 函数。首先需要包装libc
的free
函数。
module LibC
extend FFI::Library
ffi_lib FFI::Library::LIBC
# attatch free
attach_function :free, [:pointer], :void
end
现在我们可以访问free
,我们可以附加该函数并将其包装在 ruby 模块函数中。我还包含了一个辅助方法来检查有效的字符串参数。
module MyModule
class << self
extend FFI::Library
# use ffi_lib to include the library you are binding
def function(str)
is_string(str)
ptr = ffi_function(str)
result = String.new(ptr.read_string)
LibC.free(ptr)
result
end
private
# attach function and alias it as ffi_function
attach_function :ffi_function, :function, [:string], :pointer
# helper to verify strings
def is_string(object)
unless object.kind_of? String
raise TypeError,
"Wrong argument type #{object.class} (expected String)"
end
end
end
end
就是这样,希望对遇到类似问题的人有所帮助。
关于c - 如何使用 ruby ffi 附加一个返回字符串的 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24547753/