How to copy a buffer into a struct?

I'm receiving messages from an nRF24L01 into a buffer:

char myRXbuffer[33];

if (radio.available()) {
      radio.read(&myRXbuffer, 32);
      newDataFlag = true;
}

There are a few different types of message, and I use the first byte to differentiate them. I've defined my different message types as structs. Simplified, they look a bit like this:

struct voltagesMessageStruct {
  unsigned char messageType; // volts message type is 1
  unsigned char voltsMain;
  unsigned char voltsRes;
  unsigned int voltsSolar;
  // . . . continued until I've used up all 32 bytes
}

struct currentsMessageStruct {
  unsigned char messageType; // amps message type is 2
  unsigned int ampsLoad;
  unsigned char ampsSolar;
  unsigned char ampsReserve;
  // . . . continued until I've used up all 32 bytes
}

// make some instances
voltagesMessageStruct myVoltsMessage;
currentsMessageStruct myCurrentsMessage;

So I now have a 32 byte buffer, and checking, say, (myRXbuffer[0]==2) tells me it's structured like myCurrentsMessage. What syntax should I use to copy myRXbuffer into myCurrentsMessage?

Thoughts:

  • I want to copy it rather than just "cast" it, so I can continue to use the buffer for further readings
  • I could copy it long-hand, by going through each element of the struct and assigning the right bytes (or pairs of bytes, if the element is an int) but that requires a separate procedure for each structure, and is a pain to maintain.

What syntax should I use to copy myRXbuffer into myCurrentsMessage?

How do you go the other direction?

If you simply cast the myCurrentsMessage instance, then you probably could get away with using memcpy() to copy the buffer to the struct instance.

You do not want a pointer to the array, but a pointer to the first element:

radio.read(&myRXbuffer, 32);

//Needs to be
radio.read(myRXbuffer, 32);

But, you'll need the address of the structure.

memcpy( &myVoltsMessage, myRXbuffer, sizeof( myVoltsMessage ) );

Or you can add a constructor to the objects which can parse the data themselves.

The other direction happens on another Arduino (my transmitter). The same structs are defined there:

// Transmitter code:
// structs already defined in a header file; make some instances:
voltagesMessageStruct myVoltsMessage;
currentsMessageStruct myCurrentsMessage;

So, depending on what the transmitter wants to send, it just does this sort of thing:

// if it's time to send a "voltages" message:
radio.write (&myVoltsMessage, sizeof(voltagesMessageStruct)); // sizeof will always be 32 bytes by design

My problem is how to correctly and politely deal with the reception of what is now a blob of 32 bytes.

So at the receiver end, can I just do:

// if the first byte indicates it's a "volts" type message:
memcpy ( &myRXbuffer, &myVoltsMessage, 32 );

?

Ahhh - thanks pYro_65 - I'll give that a go.