我有通过 FFI gem 将结构传递给本机 Rust 库的 ruby 代码。
结构包含一个字符串字段。我需要能够在 Ruby 端指定字符串。
class MyStruct < FFI::Struct
layout :s1, :string,
:field2, :uint32,
# other fields
我试过这个:
def initialize(ruby_str)
self[:s1] = ruby_str
# [.......]
并得到了这个:
`[]=': Cannot set :string fields (ArgumentError)
这会导致分段错误:
def initialize(ruby_str)
p1 = FFI::MemoryPointer.from_string(ruby_str)
self[:content] = p1
self[:len] = ruby_str.length
我已经阅读了有关此问题的信息,但没有找到明确的解决方案,也没有找到示例。我需要能够至少从 Ruby传递一个字符串字段 (一种方式,即)。
此外,还将从本机 Rust 库接收的字符串(不是 NULL 终止,但在单独的字段中指定长度)转换为 Ruby 字符串。
那怎么办呢?