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

通过CXX实现C++与Rust交互:connect函数Rust声明报错解决

使用CXX库实现C++与Rust集成的函数声明问题

我正在用CXX库做C和Rust的集成,C头文件myclient.h中的函数签名如下:

public:
bool connect(const char * host, int port, int clientId = 0);

我在main.rs中尝试了几种声明方式:

fn connect(host: &mut , port: u64, clientId: u64 ) -> bool;
fn connect(host: *char , port: u64, clientId: u64 ) -> bool;
fn connect(host: *const char , port: u64, clientId: u64 ) -> bool;

但均报错,错误信息:

error[cxxbridge]: unsupported type: char
   ┌─ src/main.rs:15:33
   │
15 │         fn connect(host: *const char , port: u64, clientId: u64 ) -> bool;
   │                                 ^^^^ unsupported type

调整后又出现新错误:pointer argument requires that the function be marked unsafe,当前代码如下:

#[cxx::bridge(namespace = "com::enserio")]
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>;
        
        fn init_connect(&self, host: *const c_char , port: i32, client_id: i32) -> bool;
   }
}

对应的错误信息:

error[cxxbridge]: pointer argument requires that the function be marked unsafe
   ┌─ src/main.rs:16:32
   │
16 │         fn init_connect(&self, host: *const c_char , port: i32, client_id: i32) -> bool;
   │                                ^^^^^^^^^^^^^^^^^^^ pointer argument requires that the function be marked unsafe

正确的声明写法

  1. 类型匹配修正:CXX库不支持直接使用char类型,需引入std::os::raw::c_char对应C的char;同时C的int对应Rust的i32,而非u64。
  2. 标记unsafe函数:包含原始指针参数的函数必须单独标记为unsafe,CXX的extern "C++"块本身不需要unsafe修饰。

修正后的代码:

#[cxx::bridge(namespace = "com::enserio")]
mod ffi {
    use std::os::raw::c_char;

    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>;
        
        // 单独标记该函数为unsafe
        unsafe fn init_connect(&self, host: *const c_char, port: i32, client_id: i32) -> bool;
    }
}

额外说明

  • C++的默认参数clientId = 0会被CXX自动处理,Rust调用时可省略最后一个参数,默认传入0。
  • 调用unsafe函数时必须在unsafe块中执行,确保指针指向有效内存且生命周期合规:
fn main() {
    let client = ffi::new_twsapi_client();
    let host = b"localhost\0".as_ptr() as *const c_char;
    
    unsafe {
        let connected = client.init_connect(host, 7496, 0);
        println!("Connected: {}", connected);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:25:27