0

I need to send measurements via ethernet from an embedded board to a PC application developed in c# which will plot and save it.

The data in the board is formatted in the following way:

    typedef struct
    {
        float current[200];
        float ctrl_voltage[200];
        float speed;
        float position;
    }logData_t;

    logData_t embedded_data[6];

I am able to receive embedded_data in the c# application in a byte[] buffer, the question is, how do I convert this buffer in a format similar to the one shown above so that I can access the different fields in a consistent way?

Thank you for the suggestions.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Paolo
  • 17
  • 2
  • this might be useful to you: https://stackoverflow.com/questions/33022660/how-to-convert-byte-array-to-any-type/33022788 – developer Mar 13 '20 at 08:49
  • You can try this https://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-sharp-from-a-byte-array – Voodoo Mar 13 '20 at 08:58
  • Instead of sending the binary array of structures which heavily depends on your compiler and architecture, I suggest to convert the data to/from a well defined data exchange format, e.g. a text format. – Bodo Mar 13 '20 at 10:03
  • @Bodo you mean convert for example the value 2.61 to ASCII "2.61" and send a string representation? – Paolo Mar 13 '20 at 11:11
  • @PaoloMattachini Converting a float number to a string is one option and part of the whole task. You also have to define how you separate the numbers and how the numbers correspond to the structure fields or array elements. You could add markers/keys or define a fixed format. A binary data exchange format is also possible if it is well defined and independent from your platform. See also https://en.wikipedia.org/wiki/Serialization – Bodo Mar 13 '20 at 12:12

1 Answers1

0

as a struct in C# logData_t could look like this:

struct logData_t {
  fixed float current[200];
  fixed float ctrl_voltage[200];
  float speed;
  float position;
}

to use it you probably will have to load your data into unmanaged memory wich you get can get like:

logData_t* data = stackalloc logData_t[length];

and then use Marshal.Copy to load your raw data into it

but if you want to use pointers in C# you also have to set the allow unsafe code compile option

you can then access it like this:

logData_t* log = data[i];
float speed = log->speed;
Patrick Beynio
  • 788
  • 1
  • 6
  • 13
  • Thank you for the suggestion, I tried it out and it works. Not being a C# developer I need to ask though: what is the downside to use unsafe code? – Paolo Mar 13 '20 at 11:03
  • basically *unsafe code* only allows for the use of pointers. but if you use pointers you are also almost always using unmanaged memory and using unmanaged memory can easily lead to memory leaks. but stackalloc is rather save since the memory is automatically freed when the method exits – Patrick Beynio Mar 13 '20 at 11:10