cxx icon indicating copy to clipboard operation
cxx copied to clipboard

How to get data from a struct in C++?

Open hanusek opened this issue 4 years ago • 3 comments

Hello. I am doing a binding from Rust to C++. I have a problem with access to structs fields in C++. How to do correct binding? Please help me.

Rust:

#[derive(Serialize, Deserialize, Clone, PartialEq, PartialOrd, Debug)]
pub enum Value
{
    BOOL(bool),
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    F32(f32),
    F64(f64),
    STRING(String),
    Timestamp(u32),
    Timestamp64(u64)
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Hash)]
pub struct Var
{
    pub index: String,
    pub address: Value
}

pub fn test_var() -> Box<Var>
{
     let v = Var{index: String::from("1"), address: Value::U8(23)};
    println!("Var: {:#?}", v);
    return Box::new(v);
}

#[cxx::bridge]
mod ffi {
    #[namespace = "rust_part"]
    extern "Rust" 
    {
        type Var;
        type Value;
        fn test_var() -> Box<Var>;
    }
}

C++:

auto v = test_var();
// How to get v.index and v.address?

@dtolnay how to get data (fields) from a struct? Perhaps a better way would be to pass a callback function from C++... but passing a function pointer from C++ to Rust is not implemented yet :|

My library is written in Rust. I want do interfaces for C++ (calling rust function in C++). What's the best way to do this?

hanusek avatar Nov 06 '21 15:11 hanusek

Hallo. I was able to solve a similar problem recently. May be you can use it as well. See https://github.com/dtolnay/cxx/issues/957

eddi0815 avatar Nov 08 '21 13:11 eddi0815

Hallo. I was able to solve a similar problem recently. May be you can use it as well. See #957

Thx for your reply but... You have your stuct's in C++ (Data2Cpp and AliasEntry). I have in Rust.

hanusek avatar Nov 08 '21 13:11 hanusek

Look in target/cxxbridge/{cratename}/src/lib.rs.h for the Box template declaration to see the supported methods. Box is a typical smart pointer e.g.test_var()->index, etc.

davidcopp avatar Dec 14 '21 16:12 davidcopp