I am trying to pass a string in Ruby to a rust executable, manipulate it and pass the manipulated string back.
So far I can pass the string in and return it but I am at a loss as to how to convert it into a rust string, manipulate it and then pass it back to ruby. Here is what I have so far:
// 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
CStr
is not a FFI-safe type and should not be used like this. You should be using*const libc::c_char
. Secondly, the answer depends entirely on who, exactly, owns the resulting string. Does Ruby manage it? If so, how? Which heap does it need to be allocated on? Does Rust still own it? If so, how do you provide a cleanup function? All I can recommend is to find out how to do this in C, then just do it that way in Rust.