在C / C ++中直接写入内存地址的最短代码是什么? [英] What's the shortest code to write directly to a memory address in C/C++?

查看:95
本文介绍了在C / C ++中直接写入内存地址的最短代码是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为没有内存保护的嵌入式系统编写系统级代码(在ARM Cortex-M1上,用gcc 4.3编译),需要直接读/写内存映射寄存器。到目前为止,我的代码看起来像这样:

I'm writing system-level code for an embedded system without memory protection (on an ARM Cortex-M1, compiling with gcc 4.3) and need to read/write directly to a memory-mapped register. So far, my code looks like this:

#define UART0     0x4000C000
#define UART0CTL  (UART0 + 0x30)

volatile unsigned int *p;
p = UART0CTL;
*p &= ~1;

有没有更短的方式(代码更短,我的意思),不使用指针?我正在寻找一种方法来写这么短的实际分配代码(如果我不得不使用更多的#defines就没问题):

Is there any shorter way (shorter in code, I mean) that does not use a pointer? I looking for a way to write the actual assignment code as short as this (it would be okay if I had to use more #defines):

*(UART0CTL) &= ~1;

到目前为止,我尝试的任何事情都是由gcc抱怨它无法分配给lvalue的东西。 。

Anything I tried so far ended up with gcc complaining that it could not assign something to the lvalue...

推荐答案

我想成为一个nitpick:我们在说C或C ++吗?

I'd like to be a nitpick: are we talking C or C++ ?

如果C,我推迟到Chris的回答(我想要删除C ++标记)。

If C, I defer to Chris' answer willingly (and I'd like the C++ tag to be removed).

如果C ++,建议不要使用那些讨厌的C-Casts和 #define

If C++, I advise against the use of those nasty C-Casts and #define altogether.

惯用的C ++方法是使用全局变量:

The idiomatic C++ way is to use a global variable:

volatile unsigned int& UART0 = *((volatile unsigned int*)0x4000C000);
volatile unsigned int& UART0CTL = *(&UART0 + 0x0C);

我声明一个键入的全局变量,它将遵守范围规则宏)。

I declare a typed global variable, which will obey scope rules (unlike macros).

它可以很容易地使用(不需要使用 *()), !

It can be used easily (no need to use *()) and is thus even shorter!

UART0CTL &= ~1; // no need to dereference, it's already a reference

如果你想它是指针,将是:

If you want it to be pointer, then it would be:

volatile unsigned int* const UART0 = 0x4000C000; // Note the const to prevent rebinding

但是使用 const 指针不能为null?这在语义上为什么引用被创建为

But what is the point of using a const pointer that cannot be null ? This is semantically why references were created for.

这篇关于在C / C ++中直接写入内存地址的最短代码是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆