cxx icon indicating copy to clipboard operation
cxx copied to clipboard

pass char[] as the parameter to c++ function

Open smileheart1990 opened this issue 3 years ago • 1 comments

thanks for this crate, i am faced with a problem, i want to call a C++ function in rust, the c++ code detail is like bellow,

typedef char TThostFtdcBrokerIDType[11]; //struct struct CThostFtdcFensUserInfoField { TThostFtdcBrokerIDType BrokerID; TThostFtdcUserIDType UserID; TThostFtdcLoginModeType LoginMode; };

// function virtual void RegisterFensUserInfo(CThostFtdcFensUserInfoField * pFensUserInfo) = 0;

my question is, did the cxx support the struct like char[11]? i didnt see this in the official support list. or can help advise this ?

smileheart1990 avatar Mar 07 '22 06:03 smileheart1990

Yes, you'd need to give some Rust type which has a matching layout as TThostFtdcBrokerIDType. For example:

use std::os::raw::c_char;
use cxx::{type_id, ExternType};

#[repr(transparent)]
pub struct TThostFtdcBrokerIDType([c_char; 11]);

unsafe impl ExternType for TThostFtdcBrokerIDType {
    type Id = type_id!("TThostFtdcBrokerIDType");
    type Kind = cxx::kind::Trivial;
}

#[cxx::bridge]
pub mod ffi {
    struct CThostFtdcFensUserInfoField {
        BrokerID: TThostFtdcBrokerIDType,
        //...
    }

    extern "C++" {
        include!("path/to/header.h");

        type TThostFtdcBrokerIDType = crate::TThostFtdcBrokerIDType;
    }
}

(You need at least cxx version 1.0.66 for this.)

i didnt see this in the official support list. or can help advise this ?

You were probably looking at the list of built-in bindings. Something doesn't need a built-in binding in general for you to use that type. You can fill in your own ExternType impl instead for any type, as above.

dtolnay avatar Mar 08 '22 20:03 dtolnay