簡體   English   中英

如何使用 cxx crate 調用 C++ 構造函數?

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

我發現了這個問題,但它已經有 3 年歷史了,從那時起,像cxx這樣的箱子就出現了。 現在是否可以從 Rust 構造一個 C++ object,還是我仍然需要創建一個墊片?

就構造函數按值“返回”C++ 類型而言,它們不可轉換為 Rust,因為 Rust 移動 (memcpy) 與 C++ 移動不兼容(可能需要調用移動構造函數)。 將任意構造函數轉換為fn new() -> Self是不正確的。

您可以使用 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM