简体   繁体   English

如何将 C 结构传递给 Rust?

[英]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. 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.但是,它使用 cty crate,它必须由某种脚本生成。

I want to do things more easily as there is very few things I need to pass.我想更轻松地做事情,因为我需要通过的事情很少。 Just some strings ( char* ) and numbers.只是一些字符串( char* )和数字。

I already sucessfully passed a single uint8_t from C to Rust.我已经成功地将单个uint8_t从 C 传递到 Rust。

I'm now trying this on the Rust side:我现在在 Rust 端尝试这个:

#[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++:在 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?但是为什么我无法访问 Rust 上的结构成员? And possibly it won't work either, I may need to convert the char to a string.而且可能它也不起作用,我可能需要将 char 转换为字符串。

I guess this would work:我想这会起作用:

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

The pointer itself does not have an address field.指针本身没有address字段。 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 });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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