c - 如何使用 ruby​​ ffi 附加一个返回字符串的 C 函数?

标签 c ruby ffi ruby-ffi

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

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

最佳答案

经过一番工作并在 irb 中搞乱之后,我弄清楚了如何安全地包装返回 char * 的 C 函数。首先需要包装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

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

关于c - 如何使用 ruby​​ ffi 附加一个返回字符串的 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24547753/

相关文章:

ruby - Sidekiq 作业在 Heroku 上排在队列中

ruby-on-rails - MySQL 问题 - RAILS_ENV=production bundle exec rake db :migrate

ruby - "require"Ruby 中的管理

c - 学习 gcc 内部结构

c - scanf 保留出现的输出

material-ui - 如何在 reason-react 绑定(bind)中跨组件组合 Prop ?

function - 在语言层面, `ccall` 到底是什么?

c - 如何从 C 调用 Clojure 函数?

c - glibc 2.23 中的 fflush 行为更改

c - 从 pthread C 调用时 read() 不起作用