如何在C中将64位值转换为32位指针时避免警告PE1053?

huangapple go评论86阅读模式
英文:

How to avoid warning PE1053 when casting a 64-bit value to a 32-bit pointer in C?

问题

我想支持我的代码的32位和64位版本。
我的架构有一个静态的非易失性内存,可以在其中存储数据。但变量大小是静态的,所以我需要更改它。因此,我使用一个64位变量来存储地址指针。这适用于32位和64位。

在初始化阶段,我将地址存储在一个64位变量中(u64前缀表示无符号整数64位变量)。

初始化

extern MEMORY tNonVolatileMemory;
MY_TYPE tType;

// 在32位版本中可以是32位
tNonVolatileMemory.u64Address = &tType;

当我想要重新使用这个地址时,会出现编译器错误:

警告[Pe1053]:从整数到较小指针的转换

运行时

extern MEMORY tNonVolatileMemory;
MY_TYPE* ptType;

ptType = (MY_TYPE*)tNonVolatileMemory.u64Address;

是否有编程方法可以避免这个警告?

我尝试首先将其转换为void指针以避免编译器警告。

英文:

I'd like to support 32-Bit and 64-Bit Version of my code.
My architecture has a static non volatile memory, where I can store data. But the variable size is static, so I change it. So I use a 64 Bit variable to store a address pointer. This works for 32 bit & 64 bit.

I store in the initialization phase a address to a 64-Bit variable (u64 prefix means unsigned int 64 bit variable).

Init

extern MEMORY tNonVolatileMemory;
MY_TYPE tType;

// Can be 32 bit in 32 Bit version
tNonVolatileMemory.u64Address = &tType;

When I'd like to re-use the address there occures a Compiler error:

Warning[Pe1053]: conversion from integer to smaller pointer

Runtime

extern MEMORY tNonVolatileMemory;
MY_TYPE* ptType; 

ptType = (MY_TYPE*)tNonVolatileMemory.u64Address;

Is there any programming methodes to avoid this warning?

I tried to cast fist to a void pointer to avoid the compiler warning

答案1

得分: 3

如何在C语言中将64位值强制转换为32位指针时避免警告PE1053?

"我使用一个64位变量来存储地址指针"

不要进行强制转换,而是使用指针变量来存储指针。

extern void *tNonVolatileMemory;

tNonVolatileMemory = &tType;

如果希望该变量在32位地址机器和64位地址机器上始终占用相同的空间,可以使用一个联合(union)。

_Static_assert(sizeof(void *) <= sizeof(uint64_t), "Pointer too large");
union {
  void *ptr;
  uint64_t u64;
} tNonVolatileMemory;

tNonVolatileMemory.ptr = &tType;

注意:在代码中,不需要HTML编码的字符转义,因此可以直接使用&而不是&amp;

英文:

> How to avoid warning PE1053 when casting a 64-bit value to a 32-bit pointer in C?
> "I use a 64 Bit variable to store a address pointer"

Instead of casting, use a pointer variable to store a pointer.

extern void *tNonVolatileMemory;

tNonVolatileMemory = &amp;tType;

If wanting that variable to always take up the same space on 32-address machines versus 64-bit address machines, then use a union.

_Static_assert(sizeof (void *) &lt;= sizeof(uint64_t), &quot;Pointer too large&quot;);
union {
  void *ptr;
  uint64_t u64;
} tNonVolatileMemory;

tNonVolatileMemory.ptr = &amp;tType;

huangapple
  • 本文由 发表于 2023年6月1日 21:50:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定