2

I have an external C++ library that I want to use from rust. For this I use bindgen to map the function calls. The C++ function I want to use fills a (C++) string vector and has the signature:

short REQ_MList(std::vector<std::string> *list)

Bindgen generates the rust function:

pub fn REQ_MList(list: *mut std_vector) -> ::std::os::raw::c_short

Now I don't know how to handle this data type std_vector.

I tried to generate the std_vector struct and provide a raw pointer to it, which compiles but (of course) fails.

let mut list=std_vector{_Mypair: (0)};
let list_ptr:*mut std_vector= &mut list;
REQ_MList(listptr);

What is the correct way to handle this C++ data type. I haven't found any documentation about this topic.

1 Answers1

6

What is the correct way to handle this C++ data type.

There isn't one, as far as Rust is concerned, std::vector is an opaque type, even using it by value (not behind a pointer) is no bueno. It can only be created and manipulated through the API you provide.

I would very strongly recommend against exposing any C++ type over a C API, that's a sure-fire way of shooting your foot up to the knee: C++ does not have a stable ABI, to say nothing of the stds (of which there are multiple non-ABI-compatible implementations), and C++'s implicit operations (e.g. copy / move ctor, dtor) will not get implicitly translated.

If you exclusively want to communicate between C++ and Rust, you can instead use cxx, which provides bridges to std, which has bridges for several std types.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • Thank you. I also had this impression that this doesn't work at all. I will give cxx a try. – Udo Eisenbarth Feb 24 '23 at 13:27
  • Depends on your definition of "works". C++ does not preclude putting C++ stuff in `extern "C"` blocks at all (technically Rust doesn't either but it at least has a warning enabled by default). However the effect is unspecified, and it's a good way to have segfaults *at best*, and at worst very strange and hard to reproduce issues. [Been there, done that, just finding out what the was happening was an experience](https://stackoverflow.com/q/75314830/8182118). – Masklinn Feb 24 '23 at 15:06