I'm trying to build Octave functions in Rust. Octave's API is in C++, so I've generated bindings using rust-bindgen. I'm currently working through the problems that occur when trying to generate bindings that include std::string. It would be nice if I could leave it opaque and valid pointer to a C++ std::string. Would it be possible to build a utility function on the C++ side any time I needed to pass in a C++ std::string?
I was naive when I first attempted this. It is clearly wrong. A Rust std::ffi:CString is for C strings, not C++ strings. I found this recent blog helpful when comparing the two. My first attempt looks like this:
#![allow(non_snake_case)]
#![allow(unused_variables)]
extern crate octh;
// https://thefullsnack.com/en/string-ffi-rust.html
use std::ffi::CString;
#[no_mangle]
pub unsafe extern "C" fn Ghelloworld (shl: *const octh::root::octave::dynamic_library, relative: bool) -> *mut octh::root::octave_dld_function {
let name = CString::new("helloworld").unwrap();
let pname = name.as_ptr() as *const octh::root::std::string;
std::mem::forget(pname);
let doc = CString::new("Hello World Help String").unwrap();
let pdoc = doc.as_ptr() as *const octh::root::std::string;
std::mem::forget(pdoc);
octh::root::octave_dld_function_create(Some(Fhelloworld), shl, pname, pdoc)
}
pub unsafe extern "C" fn Fhelloworld (args: *const octh::root::octave_value_list, nargout: ::std::os::raw::c_int) -> octh::root::octave_value_list {
let list_ptr = ::std::ptr::null_mut();
octh::root::octave_value_list_new(list_ptr);
::std::ptr::read(list_ptr)
}
I need to pass in the function name and documentation as strings to octave_dld_function_create. I wish there was a CppString that I could use instead. Any suggestions on how to proceed?
std::stringis a mandated interface, not a mandated implementation, and if you want to pass anything by value you at least need to know its size/layout.)gcc -dumpversionand the stdlib is libstdc++.so.6 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 fromldconfig -p | grep stdc++. stackoverflow.com/a/10355215/23059_GLIBCXX_USE_CXX11_ABIdefined? ;-] Point being, if it hasn't been abstracted properly in C++-building tools, doing so elsewhere has a very slim chance. E.g. my system has libc++, libstdc++, and Dinkumware stdlibs available.-lstdc++referenced in some of the Octave build files. I'm not sure I need something abstract. I can add a function to the Octave libraries when I build it.-lstdc++is a linker command, which only implies some (shared) object files to link to; because even the C++ compiler doesn't know the answer to the "what is astd::string, anyway?" question other than the source code you feed to it.