在嵌入式设备上投射指针 [英] Casting pointers on embedded devices

查看:31
本文介绍了在嵌入式设备上投射指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 32 位嵌入式系统(redbee econotag 运行 contiki OS 以便具体).

uint32_t 数组[2];数组[0] = 0x76543210;数组[1] = 0xfedcba98;uint8_t* 点 = ((uint8_t*)array)+1;printf("%08x \n", *(uint32_t*)point );

在我的电脑上输出:

98765432

嵌入式设备上的输出:

10765432

我的计算机按照我的预期运行,但是嵌入式设备在到达单词末尾时似乎会回绕.为什么会发生这种情况?

解决方案

您的目标redbee econotag"被声明为具有 ARMv4 架构的 ARM7.ARMv4 不像 ARMv7 或英特尔机器那样提供未对齐的内存访问.

引自 ARM 的文档:

<块引用><块引用>

在 ARMv4 和 ARMv5 架构上,在 ARMv6 架构上(取决于其配置方式),访问内存中未对齐的数据时需要小心,以免返回意外结果.例如,当使用传统指针读取 C 或 C++ 源代码中的字时,ARM 编译器会生成使用 LDR 指令读取字的汇编语言代码.当地址是四的倍数时,这会按预期工作,例如,如果它位于字边界上.但是,如果地址不是四的倍数,LDR 将返回一个旋转的结果,而不是执行真正的未对齐字加载.通常,这种轮换不是程序员所期望的.

I encountered a strange problem when casting and modifying pointers on a 32bit embedded system (redbee econotag running contiki OS to be specific).

uint32_t array[2];
array[0] = 0x76543210;
array[1] = 0xfedcba98;

uint8_t* point = ((uint8_t*)array)+1;

printf("%08x \n", *(uint32_t*)point );

output on my computer:

98765432

output on embedded device:

10765432

My computer behaves as I expect it to, the embedded device however seems to wrap around when it reaches the end of the word. Why does this happen?

解决方案

Your target "redbee econotag" is stated as an ARM7 which has ARMv4 architecture. ARMv4 doesn't provide unaligned memory access like an ARMv7 or an intel machine.

Quoting from ARM's documentation:

On ARMv4 and ARMv5 architectures, and on the ARMv6 architecture depending on how it is configured, care needs to be taken when accessing unaligned data in memory, lest unexpected results are returned. For example, when a conventional pointer is used to read a word in C or C++ source code, the ARM compiler generates assembly language code that reads the word using an LDR instruction. This works as expected when the address is a multiple of four, for example if it lies on a word boundary. However, if the address is not a multiple of four, the LDR returns a rotated result rather than performing a true unaligned word load. Generally, this rotation is not what the programmer expects.

这篇关于在嵌入式设备上投射指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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