简体   繁体   English

将 int 变量的值赋给 int 指针

[英]Assign value of int variable to int pointer

I have the following C function used in an embedded software project .我在嵌入式软件项目中使用了以下 C 函数。 It's also used for the verification of the hardware and not in production.它还用于验证硬件而不是用于生产。

void reg_read(int addr) {
   int result;
   int* reg_addr = (int*)(addr); // I cast the value of the addr variable to the reg_addr pointer hoping that it would point to the address stored in addr
   result = (*reg_addr); // this should trigger a read transaction on the AXI interface of the ARM CPU that I'm simulating
}
// later on...in the main function
reg_read(0x08000704);

The embedded software runs in a simulated environment(using QEMU+SystemC) and I can see if the AXI read transaction happens or not.嵌入式软件在模拟环境中运行(使用 QEMU+SystemC),我可以查看 AXI 读取事务是否发生。 In this case it doesn't happen.在这种情况下,它不会发生。

However, if I assign a constant value to the pointer like int* reg_addr = (int*)0x08000704;但是,如果我为指针分配一个常量值,例如int* reg_addr = (int*)0x08000704; then the AXI transaction happens.然后 AXI 事务发生。

I assume the compiler generates different instructions in each case.我假设编译器在每种情况下都会生成不同的指令。 I also tried to declare reg_addr as volatile int* reg_addr;我还尝试将 reg_addr 声明为volatile int* reg_addr; but it didn't work either.但它也不起作用。

Is there a portable and compliant way of casting the value of an int variable to an int pointer?是否有一种可移植且兼容的方式将 int 变量的值转换为 int 指针?

Your question is:你的问题是:

Is there a portable and compliant way of casting the value of an int variable to an int pointer?是否有一种可移植且兼容的方式将 int 变量的值转换为 int 指针?

There is not.没有。 Summed up from the comments:从评论中总结:

Conversion of an integer to a pointer is implementation defined - Antti Haapala将整数转换为指针是实现定义的 - Antti Haapala

It was suggested that you use uintptr_t or similar which is a good suggestion from Eugene Sh.有人建议你使用 uintptr_t 或类似的,这是 Eugene Sh 的一个很好的建议。

In the example of uintptr_t以 uintptr_t 为例

uintptr_t = unsigned integer type capable of holding a pointer

From the vadefs.h file from the Microsoft Visual C++ header file vadefs.h it is defined as:从 Microsoft Visual C++ 头文件 vadefs.h 的 vadefs.h 文件中,它被定义为:

#ifdef _WIN64
    typedef unsigned __int64  uintptr_t;
#else
    typedef unsigned int uintptr_t;
#endif

In this manner, if you compile for x86 it would resolve to a 32bit data type and for x64, a 64 bit data type.以这种方式,如果您针对 x86 进行编译,它将解析为 32 位数据类型,而对于 x64,则将解析为 64 位数据类型。

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

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