0

I have a struct in C in my Embedded MCU, it's something like this

struct setting_registers
{
uint16_t CNT;
char name[32];
float calibrate[4][16];
int some_setting;
...
about 1000 elements!
};

I have transferred the Struct into my C# app with serial port, now I have a byte array that contains my Struct from the MCU, something like this

int bytes = serialPort.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort.Read(buffer, 0, bytes);

Now I want to have a similar Struct or class in C# and extract every info from this received byte array, I wanted to do a brute force casting like this,

int CNT = 0;
CNT = buffer[0]*256 + buffer[1] ;

But it will take ages! and if I change the struct in my MCU then I should do all sort of things by hand in C# code too! I wanted to know if there is a more clever way of doing it?

I have done the Struct serialization in the C inside the MCU like this

uint8_t objectPointer = (uint8_t)setting_registers; 
//Send Object 
for(uint16_t i=0;i<size_of_obj;i++)
{ 
     uart0_putChar(objectPointer[i]); 
}

I mean I can cast the whole struct to a pointer and send it serialy. So if I just copy and past my big struct with 1000 elemnts to C# is there a way to do something like a for loop to copy the elemnts in the recived buffer into the Struct?

ASiDesigner
  • 115
  • 1
  • 1
  • 8
  • No, that SerialPort.Read() takes ages, that data conversion certainly does not. Micro-optimizing it is very pointless. But don't write it yourself, use BitConverter.ToInt16(). If it is really big-endian then keep what you have. – Hans Passant Sep 13 '17 at 14:22
  • Thanks for the hint. In the C I have done something like this static uint8_t *objectPointer = (uint8_t*)setting_registers; //Send Object for(uint16_t i=0;i – ASiDesigner Sep 13 '17 at 14:27

0 Answers0