[英]How to read and write memory mapped registers using keyword volatile?
I met this question in an interview. 我在一次采访中遇到了这个问题。 I have no such experience.
我没有这样的经验。
So if we have two registers. 因此,如果我们有两个寄存器。 One with address 0x11111111 and the other 0x22222222.
一个地址为0x11111111,另一个地址为0x22222222。 We want to read and write it.
我们想读写它。 The first one is a 32-bit register while the second one is 64-bit.
第一个是32位寄存器,第二个是64位。 How do we do it in C?
我们如何在C语言中做到这一点? Can anyone just give me an example?
谁能给我一个例子吗?
Thanks, 谢谢,
You can use some kind of pointer or other, for example: 您可以使用某种指针或其他指针,例如:
#include <stdint.h>
uint32_t volatile * p = (uint32_t volatile *) 0x11111111;
uint64_t volatile * q = (uint64_t volatile *) 0x22222222;
++*p; // read-modify-write
(Note that this specific example is almost certainly bogus, since neither address seems to be aligned properly for the respective type.) (请注意,这个特定示例几乎可以肯定是虚假的,因为这两个地址似乎都未针对相应类型正确对齐。)
As you say, qualifying the pointers as volatile
is necessary if the values stored at those addresses can change from outside your program; 如您所说,如果可以在程序外部更改存储在这些地址上的值,则必须将指针限定为
volatile
。 with volatile
you tell the compiler that no assumptions may be made about the value (eg constant propagation or common subexpression elimination may not be done for volatile values). 使用
volatile
您告诉编译器无法对该值做任何假设(例如,对于volatile值,可能无法进行常数传播或公共子表达式消除)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.