I'm developing some embedded software, and trying to keep things a little more flexible. One of the things I want to be able to do is change a struct and have how the data is dealt with change throughout the rest of the application.
I've noticed that I can copy some data from a payload into a union, but for some reason not all of it. Here's what I'm doing:
union ConcentratorPacket {
struct PacketHeader header;
struct NetworkJoinReqPacket networkJoinReqPacket;
};
static union ConcentratorPacket latestRxPacket;
Where:
struct PacketHeader {
uint32_t sourceAddress;
uint8_t packetType;
};
struct NetworkJoinReqPacket{
struct PacketHeader header;
uint8_t maxDataLen;
};
Later on I want to move the data from a received packet into the relevant struct within this union, so I would like to do this:
memcpy(&latestRxPacket.networkJoinReqPacket, rxPacket->payload, sizeof(latestRxPacket.networkJoinReqPacket));
Where rxPacket->payload
is an array of uint8_t's, delivered in the correct order.
What I am seeing is that the packetHeader fills up nicely with this method, but the maxDataLen does not take the correct value. In fact the value it takes is payload[8] not payload[5].
The only way I've found to solve this is by doing a direct assignment for the maxDataLen, but that would need changed in every place if the struct changed for any reason, so memcpy is a preferable rather than this:
memcpy(&latestRxPacket.networkJoinReqPacket.header, rxPacket->payload, sizeof(latestRxPacket.networkJoinReqPacket.header));
latestRxPacket.networkJoinReqPacket.maxDataLen = rxPacket->payload[5];
I think what I'm seeing indicated that the memcpy is treating the maxDataLen as a uint32, right justified, but I don't know how to avoid this.
It's strange because I do a similar thing somewhere else and it works fine, but the only difference is that the equivalent to maxDataLen is a uint32, not a uint8.
Any help or direction would be greatly appreciated.