【问题标题】:How do I represent C's "unsigned negative" values in Rust code?如何在 Rust 代码中表示 C 的“无符号负”值?
【发布时间】:2020-01-07 00:16:21
【问题描述】:

我正在使用 winapi crate 从 Rust 调用 ResumeThread WinAPI 函数。

文档说:

如果函数成功,则返回值是线程之前的挂起计数。

如果函数失败,返回值为(DWORD)-1。

如何有效检查是否有错误?

在 C 中:

if (ResumeThread(hMyThread) == (DWORD) -1) {
    // There was an error....
}

在锈中:

unsafe {
    if ResumeThread(my_thread) == -1 {
            // There was an error....
    }
}
the trait `std::ops::Neg` is not implemented for `u32`

我理解错误;但是在语义上与 C 代码相同的最佳方式是什么?检查std::u32::MAX

【问题讨论】:

    标签: rust ffi signedness


    【解决方案1】:

    在 C 中,(type) expression 称为类型转换。在 Rust 中,您可以使用 as 关键字执行类型转换。我们还给字面量一个显式类型:

    if ResumeThread(my_thread) == -1i32 as u32 {
        // There was an error....
    }
    

    我个人会使用std::u32::MAX,可能会重命名,因为它们的值相同:

    use std::u32::MAX as ERROR_VAL;
    
    if ResumeThread(my_thread) == ERROR_VAL {
        // There was an error....
    }
    

    另见:

    【讨论】:

      【解决方案2】:

      是的,std::u32::MAX!0u32(相当于 C ~0UL,强调它是给定类型的全位设置值)。

      【讨论】:

        猜你喜欢
        • 2020-10-13
        • 1970-01-01
        • 2015-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多