The trick is simply to use initially a uint32_t
array of appropriate size (it can be dynamically allocated, see below my first idea, but not necessarily). Any object can be accessed at the byte level, so you can cast that uint32_t *
to a uint8_t *
and process it normally as a character buffer: you are accessing the original uint32_t
array at the byte level which is allowed by the strict aliasing rule.
When you need an uint32_t *
just cast back. As you only accessed the original array at the byte level, the lifetime of the array has not ended and the uint32_t *
point to a valid array.
Older and not so good solution
The trick here would be to have the buffer allocated by malloc
. The C standard says in the part referencing the C standard library explicitely accessible from a C++ program (*): 7.20.3 Memory management functions
... The pointer returned if the allocation
succeeds is suitably aligned so that it may be assigned to a pointer to any type of object
and then used to access such an object or an array of such objects in the space allocated...
That means that provided buffer
is the return value of a malloc
call, the standard guarantees that it can safely be casted to any other pointer type.
If you do not, you are in risk of an alignment problem because alignment for uint32_t
is higher than for uint8_t
, and using a bad aligned pointer is explicitly Undefined Behaviour.
One could argue that we are violating the strict aliasing rule here. But any common implementation will be fine with it (it would break too much existing code to reject that) and the only strictly conformant way would be to use a full memcopy of the buffer... to end with the exact same sequence of bytes with a compatible alignment!
(*) I know that C and C++ are different languages but C++ standard reference manual says in 1.2 Normative references [intro.refs]
1 The following referenced documents are indispensable for the application of this document...
— ISO/IEC 9899:1999, Programming languages — C
...
2 The library described in Clause 7 of ISO/IEC 9899:1999 and Clause 7 of ISO/IEC 9899:1999/Cor.1:2001
and Clause 7 of ISO/IEC 9899:1999/Cor.2:2003 is hereinafter called the C standard library.1
...
1) With the qualifications noted in Clauses 18 through 30 and in C.3, the C standard library is a subset of the C++ standard
library.
count
argument is probably the number of bytes (uint8_t
elements) to write, right? And if theBSP_SD_WriteBlocks
function write 32-bit words then you need to dividecount
by four or it will write to much (and go out of bounds of your buffer). – Legatee