如何使用 cxx crate 调用 C++ 构造函数?

How do I call a C++ constructor using the cxx crate?

我找到了 ,但它已经 3 岁了,从那时起,像 cxx 这样的板条箱就出现了。现在是否可以从 Rust 构造一个 C++ 对象,或者我仍然需要创建一个 shim?

就构造函数“return”按值的 C++ 类型而言,它们不可转换为 Rust,因为 Rust 移动 (memcpy) 与 C++ 移动不兼容(这可能需要移动构造函数称为)。将任意构造函数转换为 fn new() -> Self 是不正确的。

您可以使用 assumes moving without a constructor call is okay 的 bindgen 不安全地绑定它们,或者您可以使用自述文件中的“共享结构”方法,它可以在任何一种语言中安全移动,或者您可以 include! 垫片unique_ptr 或类似的结构。

最后一种方法类似于:

// suppose we have a struct with constructor `ZeusClient(std::string)`

// in a C++ header:
std::unique_ptr<ZeusClient> zeus_client_new(rust::Str arg);

// in the corresponding C++ source file:
std::unique_ptr<ZeusClient> zeus_client_new(rust::Str arg) {
  return make_unique<ZeusClient>(std::string(arg));
}

// in the Rust cxx bridge:
extern "C++" {
    include!("path/to/zeus/client.h");
    include!("path/to/constructorshim.h");

    type ZeusClient;

    fn zeus_client_new(arg: &str) -> UniquePtr<ZeusClient>;
}

在未来,CXX 很可能会包含一些针对此模式的内置内容,或者可能针对没有移动构造函数的结构的特殊情况。这在 dtolnay/cxx#280.

中进行了跟踪
extern "C++" {
    type ZeusClient;

    fn new(arg: &str) -> ZeusClient;  // will verify there is no move constructor

    fn new(arg: &str) -> UniquePtr<ZeusClient>;  // okay even with move constructor
}