简体   繁体   English

如何使用关键字volatile读写内存映射的寄存器?

[英]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.

相关问题 只读内存映射寄存器在C中用`volatile const`定义,但在C ++中只用`volatile`定义 - Read-only memory-mapped registers defined with `volatile const` in C but only `volatile` in C++ 控制C中存储器映射寄存器的读写访问宽度 - Controlling read and write access width to memory mapped registers in C 在 ARM 上的 Linux 中写入和读取内存映射设备寄存器 - WRITE and READ memory mapped device registers in Linux on ARM 读取内存映射的 IO 寄存器如何(来自数据表)并在 mmap 中使用它们 - reading Memory-Mapped IO registers How to (from datasheet) and using them in mmap 使用char和int访问内存映射寄存器之间的区别 - Difference between accessing Memory Mapped Registers using char and int 如何在用户空间中使用ioremap()API来读写uClinux中SPI闪存上的寄存器 - how to use ioremap() api from user space to read and write registers on SPI Flash memory in uClinux 在内存映射设备的情况下使用Volatile? - Usage of Volatile in case of Memory mapped Devices? 内存映射文件和指向易失性对象的指针 - memory mapped files and pointers to volatile objects 映射的文件在读取时不会占用内存,但在写入时会占用内存 - Mapped file doesn't take memory on read, but does on write 无法读写(内存映射)硬件寄存器 - Can't read and write (memory mapped) hardware register
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM