简体   繁体   English

Rust 如何将 struct 传输回 C?

[英]How can Rust transfer struct back to C?

I am building a server client app, where server is Rust and obtaining stat information for a given path and transfer it to C client.我正在构建一个服务器客户端应用程序,其中服务器是 Rust 并获取给定路径的统计信息并将其传输到 C 客户端。 I want the C client to be able to directly use the bytes, and cast it to a struct.我希望 C 客户端能够直接使用字节,并将其转换为结构。 The stat I am talking about is this struct in C. Here is my Rust representation of the stat:我正在谈论的 stat 是 C 中的这个结构体。这是我对 stat 的 Rust 表示:

#[repr(C)]
pub struct Stat {
    st_dev: u64,
    st_ino: u64,
    st_nlink: u64,
    st_mode: u32,
    st_uid: u32,
    st_gid: u32,
    st_rdev: u64,
    st_size: u64,
    st_blksize: u64,
    st_blocks: u64,
    st_atime: i64,
    st_atime_nsec: i64,
    st_mtime: i64,
    st_mtime_nsec: i64,
    st_ctime: i64,
    st_ctime_nsec: i64
}

impl Stat {
    pub fn encode(self) -> Vec<u8> {
        unsafe {
            std::slice::from_raw_parts(
                (&self as *const Stat) as *const u8,
                std::mem::size_of::<Stat>()
            ).to_owned()
        }
    }
}

However, when I find the values are not matching once I received it from my C side.但是,当我从 C 端收到值后发现值不匹配时。 Below is the value comparison for each field following the order in the struct,下面是按照结构体中的顺序对每个字段的值进行比较,

# C:
16777220
8613988721
0
0
5
0
16832
6879832142633762816
0
1327895242430480384
20
687194767360
17592186044416
0
6879832142633762816
0

#Rust:
16777220
8613988721
5
16832
501
20
0
160
4096
0
1601835746
0
1601835746
0
1601835746
309174704

Does anyone know what caused this problem?有谁知道是什么导致了这个问题? And how can I solve it?我该如何解决?

Use nix.使用尼克斯。 See https://docs.rs/nix/newest/nix/sys/stat/fn.stat.htmlhttps://docs.rs/nix/newest/nix/sys/stat/fn.stat.html

nix uses the struct stat from the libc package, which has a separate manually generated struct definition for every supported platform. nix 使用libc包中的struct stat ,它为每个支持的平台都有一个单独的手动生成的 struct 定义。 I don't precisely understand why you want to encode stat structures, but you need to keep in mind that they will most likely be mutually incompatible betweeen different architechtures, platforms, and OS versions.我不完全理解您为什么要对统计结构进行编码,但您需要记住,它们很可能在不同的体系结构、平台和操作系统版本之间相互不兼容。 That is, you can only reliably bytewise encode and decode them when the encoder and decoder are running on the same version of the same platform.也就是说,只有当编码器和解码器运行在同一平台的同一版本上时,您才能可靠地对它们进行字节编码和解码。

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

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