rust - 我如何在 Rust 代码中表示 C 的 "unsigned negative"值?

标签 rust ffi signedness

我调用 ResumeThread来自 Rust 的 WinAPI 函数,使用 winapi crate .

文档说:

If the function succeeds, the return value is the thread's previous suspend count.

If the function fails, the return value is (DWORD) -1.

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

在 C 中:

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

在 Rust 中:

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

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

最佳答案

在 C 中,(type) 表达式 称为类型转换。在 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....
}

另见:

关于rust - 我如何在 Rust 代码中表示 C 的 "unsigned negative"值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620609/

相关文章:

rust - 我的 std::ptr::copy_nonoverlapping 调用有什么问题?

c - 如何#define unsigned char* 字符串?

c - 使用 strncat 进行字符串连接会导致符号错误

ruby - Ruby 中的读/写进程内存

c - 在 Rust 中声明一个结构或变量的正确方法是什么,它可以传递给需要指针的 C 代码?

ruby - 如何将 C 常量包装在 Ruby FFI 模块中?

c - 传递参数中的指针目标的符号不同

rust - 如何指示异步函数的返回值与参数的生命周期相同?

rust - 如何从期权中转置 future ?

hash - 在 Rust 中散列读取器的正确方法?