How can I initialize sigset_t or other variables used as “out parameters” in Rust?

前端 未结 2 946
南笙
南笙 2020-12-11 10:49

I\'m trying to learn more about FFI in Rust and linking with C libraries, specifically libc. While on my "quest", I came across the following problem.

相关标签:
2条回答
  • 2020-12-11 11:23

    The standard library defines a couple of types and functions to deal with initialization. They are generic, so they can be used to initialize values of any type.

    Modern Rust suggests using MaybeUninit in most cases. Applied to your case, it would look something like:

    use std::mem::MaybeUninit;
    
    let mut new_action: libc::sigaction = MaybeUninit::zeroed().assume_init();
    let mut old_action: libc::sigaction = MaybeUninit::zeroed().assume_init();
    

    MaybeUninit was stabilized in Rust 1.36. Before that, you could use std::mem::uninitialized(), which gives you an uninitialized value. LLVM will consider the contents to be undefined, and will perform aggressive optimizations based on this. You must initialize any value before it's read.

    More appropriate to your case, there's std::mem::zeroed(), which gives you a value whose storage is filled with zeroes. This function is unsafe because such a value is not necessarily legal for all types. zeroed() is appropriate for "plain old data" (POD) types. Applied to your case, it would look something like:

    use std::mem;
    
    let mut new_action: libc::sigaction = mem::zeroed();
    let mut old_action: libc::sigaction = mem::zeroed();
    
    0 讨论(0)
  • 2020-12-11 11:29

    How about using mem::zeroed? The docs even say:

    This is useful for FFI functions sometimes, but should generally be avoided.

    0 讨论(0)
提交回复
热议问题