gpt4 book ai didi

C++ 风格的指针转换为整数

转载 作者:行者123 更新时间:2023-11-30 01:57:26 24 4
gpt4 key购买 nike

GetQueuedCompletionStatus() 的文档中, MSDN 说

This is done by specifying a valid event handle for the hEvent member of the OVERLAPPED structure, and setting its low-order bit.

假设事件是 HANDLE 类型,一个 void * 的类型定义,我如何使用 C++ 风格的转换来做到这一点?我不能直接将 |= 1 应用于指针,reinterpret_cast 只能在具有相同间接级别的类型之间进行转换,而 static_cast 也不起作用。这样做的 C++ 方法是什么,避免 C 风格的转换并使用 C++ 风格的转换为 size_t?我知道另一种方法是使用 union ,但这似乎比使用 C 风格的转换更难。

最佳答案

reinterpret_cast 是你需要的:

OVERLAPPED MyOverlapped;
// ...

MyOverlapped.hEvent = GetEvent(); // replace with whatever O/S call that is provided the event handle
ASSERT((reinterpret_cast<uintptr_t>(MyOverlapped.hEvent) & 0x1) == 0x0); // if lsbit is a flag, then OS source of hEvent better NOT have it INITIALLY set!
reinterpret_cast<uintptr_t &>(MyOverlapped.hEvent) |= 0x1;
// ...
GetQueuedCompletionStatus(..., &MyOverlapped, ...);

关于C++ 风格的指针转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18709090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com