0

我目前正在开发一个 C 字符串度量库,并且正在为 ruby​​ 编写绑定。使用ffi如何附加带有签名的函数char *function(const char *, const char *)?有问题的函数将在堆上分配一个字符串,malloc然后返回一个指向该字符串的指针。

我相信我需要将 ffi 附加函数包装在 ruby​​ 方法中,以便我可以将返回的字符串指针转换为 ruby​​ 字符串并释放旧指针。

4

1 回答 1

0

经过一些工作和混乱irb,我想出了如何安全地包装一个返回char *. 首先有必要包装libcfree功能。

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

就是这样,希望对遇到类似问题的人有所帮助。

于 2014-07-03T09:37:51.137 回答