简体   繁体   中英

How to pass a C Struct to Rust?

I've found https://rust-embedded.github.io/book/interoperability/c-with-rust.html which teaches how to pass a C Struct to Rust. However, it uses the cty crate, which have to be generated by some kind of script.

I want to do things more easily as there is very few things I need to pass. Just some strings ( char* ) and numbers.

I already sucessfully passed a single uint8_t from C to Rust.

I'm now trying this on the Rust side:

#[repr(C)]
pub struct VPNParameters {
    pub address: *mut c_char,
    pub address_size: usize,
    pub x: c_int,
}

#[no_mangle]
pub extern "C" fn passParameters(vpnParameters: *mut VPNParameters)
{
    //error: says "vpnParameters" has no address field
    println!("{}", vpnParameters.address);
}

and on C++:

struct VPNParameters {
    char* address;
    size_t address_size;
    int x;
} VPNParameters;

extern "C" void passParameters(VPNParameters* vPNParameters);

I think it's something like that. But why I can't access the struct members on Rust? And possibly it won't work either, I may need to convert the char to a string.

I guess this would work:

println!("{}", unsafe { *vPNParameters.address(i as isize) });

The pointer itself does not have an address field. To "arrive" at the struct that is pointed to, you need to dereference the pointer.

#[repr(C)]
pub struct VPNParameters {
    pub address: *mut libc::c_char,
    pub address_size: usize,
    pub x: libc::c_int,
}

#[no_mangle]
pub extern "C" fn passParameters(vpnParameters: *mut VPNParameters)
{
    // Note the asterisk operator
    println!("{:?}", unsafe { (*vpnParameters).address });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM