简体   繁体   English

将32位值转换为HANDLE

[英]Cast 32-bit value to HANDLE

I am dealing with a component that provides a 32-bit custom handle, and I'd like to wrap that using the standard windows HANDLE type. 我正在处理一个提供32位自定义句柄的组件,我想使用标准的Windows HANDLE类型将其包装。 In a legacy component, I've seen use of the following two conversion methods: 在旧版组件中,我看到了以下两种转换方法的使用:

// value is 32-bits
auto value = GetCustomHandle();

HANDLE hA = HANDLE(value);
HANDLE hB = (void*)(SIZE_T)value;

Are hA and hB always equivalent? hA和hB始终相等吗? If not, under what circumstances are they not? 如果不是,在什么情况下不是?

In this instance, I think they are always equivalent because: 在这种情况下,我认为它们总是等效的,因为:

  1. There's no difference between functional and c-like casts. 函数式和类c强制转换之间没有区别。
  2. HANDLE is equivalent to void*. HANDLE等于void *。
  3. The size of void* and SIZE_T is 32-bits on 32-bit systems, and 64-bits on 64-bit systems. void *和SIZE_T的大小在32位系统上为32位,在64位系统上为64位。

Thanks. 谢谢。

Personally, I would go with the C++ style cast: 就个人而言,我会采用C ++样式转换:

 HANDLE hCPP = reinterpret_cast<HANDLE>(value);

You may get a warning for "casting narrow type to wider type" (or whatever the terminology the compiler uses for that), in which case the expression should be: 您可能会收到“将窄型转换为宽型”(或编译器为此使用的任何术语)的警告,在这种情况下,表达式应为:

 HANDLE hCPP = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));

The type uintptr_t is guaranteed to be unsigned and match the size of a pointer. uintptr_t保证是无符号的,并且与指针的大小匹配。 Using MS-defined types will just make it less portable - not generally a big problem in Windows software, but it's certainly no benefit to make code LESS portable. 使用MS定义的类型只会使它的可移植性降低-通常在Windows软件中不是一个大问题,但是使代码LESS可移植无疑没有任何好处。

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

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