ruby 弦使用rust 并再次使用rust

标签 ruby string rust ffi

我正在尝试将 Ruby 中的字符串传递给 Rust 可执行文件,对其进行操作并将操作后的字符串传回。

到目前为止,我可以传入字符串并返回它,但我不知道如何将它转换为使用rust 字符串,对其进行操作,然后将其传回 ruby​​。这是我目前所拥有的:

// lib.rs
use std::ffi::CStr;

#[no_mangle]
pub extern fn return_string(test_str: &CStr) -> &CStr {
    // working funciton
    test_str
}

#[no_mangle]
pub extern fn manipulate_and_return_string(mystr: &CStr) -> &CStr {
    // mystr type == &std::ffi::c_str::CStr
    // println!("{:?}", mystr); => std::ffi::c_str::CStr` cannot be formatted using `:?`
    let cstr = mystr.to_bytes_with_nul();
    // println!("{:?}", mystr); => []
    // cstr type == &[u8]
    let ptr = cstr.as_ptr();
    // ptr type == *const u8
    // println!("{:?}", mystr); => 0x7fd898edb520
    let str_slice: &str = std::str::from_utf8(cstr).unwrap();
    // str type == &str
    // println!("{:?}", mystr); => ""
    let str_buf: String = str_slice.to_owned();
    // str_bug == collections::string::String
    // println!("{:?}", mystr); => ""
}
# rust.rb
require 'ffi'

module Rust
  extend FFI::Library
  ffi_lib './bin/libembed.dylib'

  attach_function :return_string, [:string], :string
  attach_function :manipulate_and_return_string, [:string], :string
end

最佳答案

感谢来自 Steve Klabnik 的指导, shepmasterDK我想出了如何在 Rust 中编写外部字符串连接函数并在 Ruby 中使用它。

// lib.rs
#![feature(libc)]
#![feature(cstr_to_str)]
#![feature(cstr_memory)]
extern crate libc;
use std::ffi::{CStr,CString};

#[no_mangle]
pub extern fn concat(s1: *const libc::c_char, s2: *const libc::c_char) -> *const libc::c_char {
    let s1_cstr = unsafe { CStr::from_ptr(s1) };  // &std::ffi::c_str::CStr
    let s2_cstr = unsafe { CStr::from_ptr(s2) };  // &std::ffi::c_str::CStr
    let s1_and_str = s1_cstr.to_str().unwrap();  // &str
    let s2_and_str = s2_cstr.to_str().unwrap();  // &str

    let mut s1_string = s1_and_str.to_string();  // collections::string::String

    s1_string.push_str(s2_and_str);
    // s1_string + s2_and_str); // same thing

    let concated_string = CString::new(s1_string).unwrap();  // std::ffi::c_str::CString

    concated_string.into_ptr() // const i8
}
# rust.rb
require 'ffi'

module Rust
  extend FFI::Library
  ffi_lib './bin/libembed.dylib'

  attach_function :concat, [:string, :string], :string
end
#calling the function in Ruby

Rust.concat('This is a ', 'cohesive sentence') # => 'This is a cohesive sentence'

关于 ruby 弦使用rust 并再次使用rust ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021453/

相关文章:

ruby-on-rails - Development.log 日志文件不记录 Rails SQL 查询

c# - 在 C# 中将整数列表转换为逗号分隔数字字符串的最简单方法是什么

rust - PathBuf::from(&some_other_pathbuf)会克隆some_other_pathbuf的数据吗?

rust - 解决通过引用获取参数的闭包的类型不匹配

rust - 交换两个本地引用会导致生命周期错误

ruby - DateTime.strptime 我做错了什么?

重启 RabbitMQ 后删除 Ruby AMQP 持久消息

ruby-on-rails - Rails + SQLite3:搜索?

c# - 使用 C# 解析 HTML 以获取内容

javascript - 从 jQuery 数组中删除逗号