我找到了 this question , 但它已经 3 岁了,从那时起,像 cxx
这样的 crate 就出现了。现在是否可以从 Rust 构造一个 C++ 对象,或者我仍然需要创建一个 shim?
最佳答案
就构造函数按值“返回”C++ 类型而言,它们不可转换为 Rust,因为 Rust 移动 (memcpy) 与 C++ 移动不兼容(这可能需要调用移动构造函数)。将任意构造函数转换为 fn new() -> Self
是不正确的。
您可以使用 bindgen 不安全地绑定(bind)它们 assumes moving without a constructor call is okay ,或者您可以使用自述文件中的“共享结构”方法,它可以在任何一种语言中安全地移动,或者您可以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
}
关于c++ - 如何使用 cxx crate 调用 C++ 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63652326/