You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C++常规构造器转为pImpl风格?CXX Rust调用问题求助

Rust调用C++类方法报错:找不到connect方法

背景

我参考cxx的Rust示例实现,示例采用了pImpl模式:

// Toy implementation of an in-memory blobstore.
//
// In reality the implementation of BlobstoreClient could be a large complex C++
// library.
class BlobstoreClient::impl {
  friend BlobstoreClient;
  using Blob = struct {
    std::string data;
    std::set<std::string> tags;
  };
  std::unordered_map<uint64_t, Blob> blobs;
};

BlobstoreClient::BlobstoreClient() : impl(new class BlobstoreClient::impl) {}

但我此前从未使用过该风格,当前TWSApiClient的构造/析构器写法如下:

TWSApiClient::TWSApiClient():
        m_osSignal(2000)//2-seconds timeout
        , m_pClient(new EClientSocket(this, &m_osSignal))
        , m_state(ST_CONNECT) // starts at m_state = 0
        , m_sleepDeadline(0)
        , m_orderId(0)
        , m_extraAuth(false) {}

TWSApiClient::~TWSApiClient()
{
    if( m_pReader ){
        m_pReader.reset();
    }
    delete m_pClient;
}

错误信息

编译Rust代码调用类方法时,提示找不到connect方法:

fn main() {
    println!("Starting TWSApiClient connect()");
    let client = ffi::new_twsapi_client();
    client.connect(4002, 333);
    println!("Finished TWSApiClient connect()");
}

错误输出:

error[E0599]: no method named `connect` found for struct `UniquePtr<TWSApiClient>` in the current scope
  --> src/main.rs:22:12
   |
22 |     client.connect(4002, 333);
   |            ^^^^^^^ method not found in `UniquePtr<TWSApiClient>`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `twsapi_grpc_server` due to previous error

完整Rust代码

#[cxx::bridge(namespace = "com::ourco")]

mod ffi {
    unsafe extern "C++" {
        include!("twsapi_grpc_server/include/twsapi-client.h");
        include!("twsapi_grpc_server/include/AvailableAlgoParams.h");
        include!("twsapi_grpc_server/include/AccountSummaryTags.h");
        include!("twsapi_grpc_server/include/Utils.h");
        type TWSApiClient;
        fn new_twsapi_client() -> UniquePtr<TWSApiClient>;
        #[allow(dead_code)]
        fn connect(self: Pin<&mut TWSApiClient>, port: i32, client_id: i32) -> bool;
    }
}

fn main() {
    println!("Starting TWSApiClient connect()");
    let _client = ffi::new_twsapi_client();
    //_client.connect(4002, 333);
    println!("Finished TWSApiClient connect()");
}

疑问

我猜测是未采用cxx示例中的pImpl风格导致的问题,是否只需将m_state(ST_CONNECT)这类初始化项移到impl类的代码块中?另外,pImpl风格是否是cxx库的必需要求?

内容的提问来源于stack exchange,提问作者Erik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:20:31