gpt4 book ai didi

c++ - 使用地址作为标量值

转载 作者:搜寻专家 更新时间:2023-10-31 00:52:20 25 4
gpt4 key购买 nike

我正在尝试使用 AfxBeginThread 来理解一些遗留代码.

据我了解,LPVOID 被定义为指向空对象的指针。我有这个功能:

Start(LPVOID pParam){
...
int iTemp = (int)pParam;
...
}

然后调用:

int ch1 = 1;
AfxBeginThread(Start(), (LPVOID)ch1);

我在为 64 位编译时收到以下编译器警告:

warning C4312: 'type cast': conversion from 'int' to 'LPVOID' of greater size

我是

  • 不能 100% 确定这是对指针的正确使用
  • 为了避免警告,我可以使用像 (LPVOID) PtrToInt(ch1) 这样的辅助函数,但这对我来说也不合适

谁能帮我理解这背后的机制?我一直试图在网上找到一个以类似方式使用 AfxBeginThread 的示例,但到目前为止都失败了。

女士 states:

The parameter is a single value. The value the function receives in this parameter is the value that was passed to the constructor when the thread object was created. The controlling function can interpret this value in any manner it chooses. It can be treated as a scalar value or a pointer to a structure containing multiple parameters, or it can be ignored.

最佳答案

出现此警告是因为您正在 64 位计算机上编译,其中 sizeof(void*)8 字节但 sizeof(int)4

处理此问题的正确方法是为 ch1 使用整数类型,它与 void 指针的大小相同。这正是 intptr_t 的用例。

因此,如果您使用ìntptr_t 来保存ch1 变量应该是安全的。另见 this question: C++: Is it safe to cast pointer to int and later back to pointer again?

关于c++ - 使用地址作为标量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52109239/

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