DWORD_PTR、INT_PTR、LONG_PTR、UINT_PTR、ULONG_PTR 何时、如何以及为什么?

2022-01-12 00:00:00 windows winapi mfc

我发现 Windows 有一些新的 Windows 数据类型

I found that Windows has some new Windows Data Types

DWORD_PTR, INT_PTR, LONG_PTR, UINT_PTR, ULONG_PTR

您能告诉我何时、如何以及为什么使用它们吗?

can you tell me when, how and why to use them?

推荐答案

*_PTR 类型被添加到 Windows API 以支持 Win64 的 64 位寻址.

The *_PTR types were added to the Windows API in order to support Win64's 64bit addressing.

由于 32 位 API 通常使用 DWORD 等数据类型传递指针,因此有必要为 64 位兼容性创建新类型,以替代 32 位应用程序中的 DWORD,但是在 64 位应用程序中使用时已扩展到 64 位.

Because 32bit APIs typically passed pointers using data types like DWORD, it was necessary to create new types for 64 bit compatibility that could substitute for DWORD in 32bit applications, but were extended to 64bits when used in a 64bit applications.

因此,例如,如果应用程序开发人员想要编写可用作 32 位或 64 位 Windows 32 位 API 的代码 SetWindowLong(HWND,int,LONG) 已更改为 SetWindowLongPtr(HWND,int,LONG_PTR)

So, for example, application developers who want to write code that works as 32bit OR 64bit the windows 32bit API SetWindowLong(HWND,int,LONG) was changed to SetWindowLongPtr(HWND,int,LONG_PTR)

在 32 位构建中,SetWindowLongPtr 只是一个解析为 SetWindowLong 的宏,LONG_PTR 同样是一个解析为 的宏>长.另一方面,在 64 位构建中,SetWindowLongPtr 是一个接受 64 位长作为其第三个参数的 API,并且 ULONG_PTRunsigned __int64.

In a 32bit build, SetWindowLongPtr is simply a macro that resolves to SetWindowLong, and LONG_PTR is likewise a macro that resolves to LONG. In a 64bit build on the other hand, SetWindowLongPtr is an API that accepts a 64bit long as its 3rd parameter, and ULONG_PTR is typedef for unsigned __int64.

通过使用这些 _PTR 类型,一个代码库可以针对 Win32 和 Win64 目标进行编译.

By using these _PTR types, one codebase can compile for both Win32 and Win64 targets.

在进行指针运算时,这些类型也应该用在需要兼容 64 位的 32 位代码中.

When performing pointer arithmetic, these types should also be used in 32bit code that needs to be compatible with 64bit.

因此,如果您需要访问包含超过 40 亿个元素的数组,则需要使用 INT_PTR 而不是 INT

so, if you need to access an array with more than 4billion elements, you would need to use an INT_PTR rather than an INT

  CHAR* pHuge = new CHAR[0x200000000]; // allocate 8 billion bytes
  INT idx;
  INT_PTR idx2;
  pHuge[idx]; // can only access the 1st 4 billion elements.
  pHuge[idx2]; // can access all 64bits of potential array space.

相关文章