Hi all I have a strange problem when I'm trying to cast buffers by arm compiler. Here an example:
char* pbuf; ... unsigned short val = *((unsigned short*)(pbuf+3));
When I compile this code, my generated assembly code uses LDRH,STRH. Then because my pbuf+3 is not multiple of 2 and those 2 instruction can only work with even value addresses, processor hangs up. What I should to do that compiler generates a code that works in all cases?
Regards
So don't do that, then!
It is always risky to assume that you can just cast any arbitrary pointer to any other arbitrary type - precisely because this is likely to fall foul of the alignment rules of the underlying architecture.
It is not a "strange" problem - it is rather to be expected!
If you've got used to doing this on an 8-bit chip, then it has only been working by luck - because 8-bit processors just happen not to care about any alignment!
You really need to do this "properly": pull the individual bytes out of the buffer and build them into the larger datatype.
Either that, or you will have to somehow ensure that the bytes in your buffer are properly aligned to be accessed as the larger data type...
"...it has only been working by luck..."
Not sure I would class it as 'luck' - When the situation, dangers and consequences are understood, it's use is extremely liberating.
In answer to the OPs situation - Look at the __packed keyword.
But remember, look into and understand the consequences.
it's use is extremely liberating
And not portable, as you well know, Sausage man.
"And not portable, as you well know, Sausage man."
It is not ***guaranteed*** to be portable. There is a (subtle) difference.
The projects on which I've used it were on 51s, Z80s, V55, 186s, 386s. No problems with portability of the relevant modules there.
It made data manipulation and storage far more efficient.
I'm now porting code to the ARM. Looked into using the __packed keyword, but probably won't use it because ARM has such extreme raw processing power.
The key to this, like nearly every other embedded task, is a thorough understanding of the low level operation of the processors.
View all questions in Keil forum