【问题标题】:How do you attach a C function that returns a string using ruby ffi?如何附加使用 ruby​​ ffi 返回字符串的 C 函数?
【发布时间】:2014-07-03 07:38:35
【问题描述】:

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

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

【问题讨论】:

    标签: c ruby ffi ruby-ffi


    【解决方案1】:

    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
    

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

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 2016-10-11
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2011-03-08
      • 2017-06-03
      相关资源
      最近更新 更多