C => C# Is there an easy way to reproduce struct casting for binary communication










0














For an USB and serial application, I implement a protocol, and in C/C++ it can be neatly done by structure casting into the buffer, which it makes it handy to encode / decode from data to a byte array, which can then be forwarded to an USB or Serial port.



The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.



Here is an example of a data packing into a char buffer.



Edit: Note that the structure is packed, which means there is no padding between the types.



#pragma pack(push,2)
typedef struct

uint32_t address ;
uint32_t len;
uint16_t crc;
FlashData;
#pragma pack(pop)


unsigned char buf[size + sizeof(FlashData)] __attribute__((aligned));

FlashData *flashData = (FlashData*) &buf[0];
flashData->address = startAddr;
flashData->len = size;
[...]



Is there a simple way to reproduce this sort of casting in C#?



Many years ago I did similar communication in C# but I remember I had to serialize data an manually unpack, which was a pain.



There are some C# example of copying C# data structure to byte arrays, but since every object and type are inherited in C#, I am not sure that would be a good solution.



Another way could be to have a solution with both C++ and C# project, C++ taking care of low level communication and C# higher level and UI management, link by DLL.




EDIT



Answer was actually given by elgonzo on the comments.



 [StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct Packet

public byte header;
public byte cmd;
public ushort address;
public ushort len;
public ushort crc;



and the GetByte method










share|improve this question



















  • 1




    "Simple way" might be relative... To convert a struct to a byte array, you can either build your byte array manually from the struct values (and vice versa), or, more conveniently, you can use interop marshalling to convert structs to byte arrays and back (see here: stackoverflow.com/questions/3278827/…). If you choose the interop marshalling approach, you might probably also need to adjust the memory layout of the struct; see here how to do that: developerfusion.com/article/84519/mastering-structs-in-c
    – elgonzo
    Nov 11 at 6:34







  • 1




    Possible duplicate of How to convert a structure to a byte array in C#?
    – elgonzo
    Nov 11 at 7:53










  • @elgonzo the question is different and ask for the possible problematic of doing so, also the end use is different as well.
    – Damien
    Nov 11 at 9:50










  • How precisely is the question different? A different end use (application scenario) is no indicator of a difference in question. (Would asking how to drive a car be everytime a different question if the use case/reason for driving a car would be different? Like "I want to drive a car myself to the cinama to watch a movie", "I want to drive a car myself to pick up groceries", "I want to drive a car myself to work". According to your reasoning the question "How to drive a car" and its answer would be different every time just because the end use is different. No...)
    – elgonzo
    Nov 11 at 9:55











  • Because serialization of a data struct from C# -> C# would not pause any problem, even with type header, but would be a problem in a C# -> C communication. It also have packing directive which is not addressed on the other question @elgonzo
    – Damien
    Nov 11 at 10:44















0














For an USB and serial application, I implement a protocol, and in C/C++ it can be neatly done by structure casting into the buffer, which it makes it handy to encode / decode from data to a byte array, which can then be forwarded to an USB or Serial port.



The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.



Here is an example of a data packing into a char buffer.



Edit: Note that the structure is packed, which means there is no padding between the types.



#pragma pack(push,2)
typedef struct

uint32_t address ;
uint32_t len;
uint16_t crc;
FlashData;
#pragma pack(pop)


unsigned char buf[size + sizeof(FlashData)] __attribute__((aligned));

FlashData *flashData = (FlashData*) &buf[0];
flashData->address = startAddr;
flashData->len = size;
[...]



Is there a simple way to reproduce this sort of casting in C#?



Many years ago I did similar communication in C# but I remember I had to serialize data an manually unpack, which was a pain.



There are some C# example of copying C# data structure to byte arrays, but since every object and type are inherited in C#, I am not sure that would be a good solution.



Another way could be to have a solution with both C++ and C# project, C++ taking care of low level communication and C# higher level and UI management, link by DLL.




EDIT



Answer was actually given by elgonzo on the comments.



 [StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct Packet

public byte header;
public byte cmd;
public ushort address;
public ushort len;
public ushort crc;



and the GetByte method










share|improve this question



















  • 1




    "Simple way" might be relative... To convert a struct to a byte array, you can either build your byte array manually from the struct values (and vice versa), or, more conveniently, you can use interop marshalling to convert structs to byte arrays and back (see here: stackoverflow.com/questions/3278827/…). If you choose the interop marshalling approach, you might probably also need to adjust the memory layout of the struct; see here how to do that: developerfusion.com/article/84519/mastering-structs-in-c
    – elgonzo
    Nov 11 at 6:34







  • 1




    Possible duplicate of How to convert a structure to a byte array in C#?
    – elgonzo
    Nov 11 at 7:53










  • @elgonzo the question is different and ask for the possible problematic of doing so, also the end use is different as well.
    – Damien
    Nov 11 at 9:50










  • How precisely is the question different? A different end use (application scenario) is no indicator of a difference in question. (Would asking how to drive a car be everytime a different question if the use case/reason for driving a car would be different? Like "I want to drive a car myself to the cinama to watch a movie", "I want to drive a car myself to pick up groceries", "I want to drive a car myself to work". According to your reasoning the question "How to drive a car" and its answer would be different every time just because the end use is different. No...)
    – elgonzo
    Nov 11 at 9:55











  • Because serialization of a data struct from C# -> C# would not pause any problem, even with type header, but would be a problem in a C# -> C communication. It also have packing directive which is not addressed on the other question @elgonzo
    – Damien
    Nov 11 at 10:44













0












0








0







For an USB and serial application, I implement a protocol, and in C/C++ it can be neatly done by structure casting into the buffer, which it makes it handy to encode / decode from data to a byte array, which can then be forwarded to an USB or Serial port.



The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.



Here is an example of a data packing into a char buffer.



Edit: Note that the structure is packed, which means there is no padding between the types.



#pragma pack(push,2)
typedef struct

uint32_t address ;
uint32_t len;
uint16_t crc;
FlashData;
#pragma pack(pop)


unsigned char buf[size + sizeof(FlashData)] __attribute__((aligned));

FlashData *flashData = (FlashData*) &buf[0];
flashData->address = startAddr;
flashData->len = size;
[...]



Is there a simple way to reproduce this sort of casting in C#?



Many years ago I did similar communication in C# but I remember I had to serialize data an manually unpack, which was a pain.



There are some C# example of copying C# data structure to byte arrays, but since every object and type are inherited in C#, I am not sure that would be a good solution.



Another way could be to have a solution with both C++ and C# project, C++ taking care of low level communication and C# higher level and UI management, link by DLL.




EDIT



Answer was actually given by elgonzo on the comments.



 [StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct Packet

public byte header;
public byte cmd;
public ushort address;
public ushort len;
public ushort crc;



and the GetByte method










share|improve this question















For an USB and serial application, I implement a protocol, and in C/C++ it can be neatly done by structure casting into the buffer, which it makes it handy to encode / decode from data to a byte array, which can then be forwarded to an USB or Serial port.



The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.



Here is an example of a data packing into a char buffer.



Edit: Note that the structure is packed, which means there is no padding between the types.



#pragma pack(push,2)
typedef struct

uint32_t address ;
uint32_t len;
uint16_t crc;
FlashData;
#pragma pack(pop)


unsigned char buf[size + sizeof(FlashData)] __attribute__((aligned));

FlashData *flashData = (FlashData*) &buf[0];
flashData->address = startAddr;
flashData->len = size;
[...]



Is there a simple way to reproduce this sort of casting in C#?



Many years ago I did similar communication in C# but I remember I had to serialize data an manually unpack, which was a pain.



There are some C# example of copying C# data structure to byte arrays, but since every object and type are inherited in C#, I am not sure that would be a good solution.



Another way could be to have a solution with both C++ and C# project, C++ taking care of low level communication and C# higher level and UI management, link by DLL.




EDIT



Answer was actually given by elgonzo on the comments.



 [StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct Packet

public byte header;
public byte cmd;
public ushort address;
public ushort len;
public ushort crc;



and the GetByte method







c# c++ serialization usb






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 at 7:37

























asked Nov 11 at 5:31









Damien

783316




783316







  • 1




    "Simple way" might be relative... To convert a struct to a byte array, you can either build your byte array manually from the struct values (and vice versa), or, more conveniently, you can use interop marshalling to convert structs to byte arrays and back (see here: stackoverflow.com/questions/3278827/…). If you choose the interop marshalling approach, you might probably also need to adjust the memory layout of the struct; see here how to do that: developerfusion.com/article/84519/mastering-structs-in-c
    – elgonzo
    Nov 11 at 6:34







  • 1




    Possible duplicate of How to convert a structure to a byte array in C#?
    – elgonzo
    Nov 11 at 7:53










  • @elgonzo the question is different and ask for the possible problematic of doing so, also the end use is different as well.
    – Damien
    Nov 11 at 9:50










  • How precisely is the question different? A different end use (application scenario) is no indicator of a difference in question. (Would asking how to drive a car be everytime a different question if the use case/reason for driving a car would be different? Like "I want to drive a car myself to the cinama to watch a movie", "I want to drive a car myself to pick up groceries", "I want to drive a car myself to work". According to your reasoning the question "How to drive a car" and its answer would be different every time just because the end use is different. No...)
    – elgonzo
    Nov 11 at 9:55











  • Because serialization of a data struct from C# -> C# would not pause any problem, even with type header, but would be a problem in a C# -> C communication. It also have packing directive which is not addressed on the other question @elgonzo
    – Damien
    Nov 11 at 10:44












  • 1




    "Simple way" might be relative... To convert a struct to a byte array, you can either build your byte array manually from the struct values (and vice versa), or, more conveniently, you can use interop marshalling to convert structs to byte arrays and back (see here: stackoverflow.com/questions/3278827/…). If you choose the interop marshalling approach, you might probably also need to adjust the memory layout of the struct; see here how to do that: developerfusion.com/article/84519/mastering-structs-in-c
    – elgonzo
    Nov 11 at 6:34







  • 1




    Possible duplicate of How to convert a structure to a byte array in C#?
    – elgonzo
    Nov 11 at 7:53










  • @elgonzo the question is different and ask for the possible problematic of doing so, also the end use is different as well.
    – Damien
    Nov 11 at 9:50










  • How precisely is the question different? A different end use (application scenario) is no indicator of a difference in question. (Would asking how to drive a car be everytime a different question if the use case/reason for driving a car would be different? Like "I want to drive a car myself to the cinama to watch a movie", "I want to drive a car myself to pick up groceries", "I want to drive a car myself to work". According to your reasoning the question "How to drive a car" and its answer would be different every time just because the end use is different. No...)
    – elgonzo
    Nov 11 at 9:55











  • Because serialization of a data struct from C# -> C# would not pause any problem, even with type header, but would be a problem in a C# -> C communication. It also have packing directive which is not addressed on the other question @elgonzo
    – Damien
    Nov 11 at 10:44







1




1




"Simple way" might be relative... To convert a struct to a byte array, you can either build your byte array manually from the struct values (and vice versa), or, more conveniently, you can use interop marshalling to convert structs to byte arrays and back (see here: stackoverflow.com/questions/3278827/…). If you choose the interop marshalling approach, you might probably also need to adjust the memory layout of the struct; see here how to do that: developerfusion.com/article/84519/mastering-structs-in-c
– elgonzo
Nov 11 at 6:34





"Simple way" might be relative... To convert a struct to a byte array, you can either build your byte array manually from the struct values (and vice versa), or, more conveniently, you can use interop marshalling to convert structs to byte arrays and back (see here: stackoverflow.com/questions/3278827/…). If you choose the interop marshalling approach, you might probably also need to adjust the memory layout of the struct; see here how to do that: developerfusion.com/article/84519/mastering-structs-in-c
– elgonzo
Nov 11 at 6:34





1




1




Possible duplicate of How to convert a structure to a byte array in C#?
– elgonzo
Nov 11 at 7:53




Possible duplicate of How to convert a structure to a byte array in C#?
– elgonzo
Nov 11 at 7:53












@elgonzo the question is different and ask for the possible problematic of doing so, also the end use is different as well.
– Damien
Nov 11 at 9:50




@elgonzo the question is different and ask for the possible problematic of doing so, also the end use is different as well.
– Damien
Nov 11 at 9:50












How precisely is the question different? A different end use (application scenario) is no indicator of a difference in question. (Would asking how to drive a car be everytime a different question if the use case/reason for driving a car would be different? Like "I want to drive a car myself to the cinama to watch a movie", "I want to drive a car myself to pick up groceries", "I want to drive a car myself to work". According to your reasoning the question "How to drive a car" and its answer would be different every time just because the end use is different. No...)
– elgonzo
Nov 11 at 9:55





How precisely is the question different? A different end use (application scenario) is no indicator of a difference in question. (Would asking how to drive a car be everytime a different question if the use case/reason for driving a car would be different? Like "I want to drive a car myself to the cinama to watch a movie", "I want to drive a car myself to pick up groceries", "I want to drive a car myself to work". According to your reasoning the question "How to drive a car" and its answer would be different every time just because the end use is different. No...)
– elgonzo
Nov 11 at 9:55













Because serialization of a data struct from C# -> C# would not pause any problem, even with type header, but would be a problem in a C# -> C communication. It also have packing directive which is not addressed on the other question @elgonzo
– Damien
Nov 11 at 10:44




Because serialization of a data struct from C# -> C# would not pause any problem, even with type header, but would be a problem in a C# -> C communication. It also have packing directive which is not addressed on the other question @elgonzo
– Damien
Nov 11 at 10:44












2 Answers
2






active

oldest

votes


















0















The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.




Unfortunately, your code would work differently on a 64-bit PC vs. 32-Bit µC.



The compilers would disagree on sizeof(unsigned long), which is 4 for most microcontroller architectures and 8 on 64-bit PC. Some µC also run big endian.



Therefore it would be a lot better to write proper serialization/deserialization code.






share|improve this answer




















  • The type can be specified as uint32_t in C and UInt32 in C#. updated types in the question.
    – Damien
    Nov 11 at 10:36











  • That still leaves the big endian <=> little endian problem.
    – Turbo J
    Nov 11 at 11:19










  • Yes but that can be solved with a small convert method
    – Damien
    Nov 12 at 4:22


















0














The BitConverter.GetBytes method converts basic data types to array of bytes.






share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246112%2fc-c-sharp-is-there-an-easy-way-to-reproduce-struct-casting-for-binary-communi%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0















    The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.




    Unfortunately, your code would work differently on a 64-bit PC vs. 32-Bit µC.



    The compilers would disagree on sizeof(unsigned long), which is 4 for most microcontroller architectures and 8 on 64-bit PC. Some µC also run big endian.



    Therefore it would be a lot better to write proper serialization/deserialization code.






    share|improve this answer




















    • The type can be specified as uint32_t in C and UInt32 in C#. updated types in the question.
      – Damien
      Nov 11 at 10:36











    • That still leaves the big endian <=> little endian problem.
      – Turbo J
      Nov 11 at 11:19










    • Yes but that can be solved with a small convert method
      – Damien
      Nov 12 at 4:22















    0















    The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.




    Unfortunately, your code would work differently on a 64-bit PC vs. 32-Bit µC.



    The compilers would disagree on sizeof(unsigned long), which is 4 for most microcontroller architectures and 8 on 64-bit PC. Some µC also run big endian.



    Therefore it would be a lot better to write proper serialization/deserialization code.






    share|improve this answer




















    • The type can be specified as uint32_t in C and UInt32 in C#. updated types in the question.
      – Damien
      Nov 11 at 10:36











    • That still leaves the big endian <=> little endian problem.
      – Turbo J
      Nov 11 at 11:19










    • Yes but that can be solved with a small convert method
      – Damien
      Nov 12 at 4:22













    0












    0








    0







    The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.




    Unfortunately, your code would work differently on a 64-bit PC vs. 32-Bit µC.



    The compilers would disagree on sizeof(unsigned long), which is 4 for most microcontroller architectures and 8 on 64-bit PC. Some µC also run big endian.



    Therefore it would be a lot better to write proper serialization/deserialization code.






    share|improve this answer













    The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.




    Unfortunately, your code would work differently on a 64-bit PC vs. 32-Bit µC.



    The compilers would disagree on sizeof(unsigned long), which is 4 for most microcontroller architectures and 8 on 64-bit PC. Some µC also run big endian.



    Therefore it would be a lot better to write proper serialization/deserialization code.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 11 at 10:24









    Turbo J

    6,51711733




    6,51711733











    • The type can be specified as uint32_t in C and UInt32 in C#. updated types in the question.
      – Damien
      Nov 11 at 10:36











    • That still leaves the big endian <=> little endian problem.
      – Turbo J
      Nov 11 at 11:19










    • Yes but that can be solved with a small convert method
      – Damien
      Nov 12 at 4:22
















    • The type can be specified as uint32_t in C and UInt32 in C#. updated types in the question.
      – Damien
      Nov 11 at 10:36











    • That still leaves the big endian <=> little endian problem.
      – Turbo J
      Nov 11 at 11:19










    • Yes but that can be solved with a small convert method
      – Damien
      Nov 12 at 4:22















    The type can be specified as uint32_t in C and UInt32 in C#. updated types in the question.
    – Damien
    Nov 11 at 10:36





    The type can be specified as uint32_t in C and UInt32 in C#. updated types in the question.
    – Damien
    Nov 11 at 10:36













    That still leaves the big endian <=> little endian problem.
    – Turbo J
    Nov 11 at 11:19




    That still leaves the big endian <=> little endian problem.
    – Turbo J
    Nov 11 at 11:19












    Yes but that can be solved with a small convert method
    – Damien
    Nov 12 at 4:22




    Yes but that can be solved with a small convert method
    – Damien
    Nov 12 at 4:22













    0














    The BitConverter.GetBytes method converts basic data types to array of bytes.






    share|improve this answer

























      0














      The BitConverter.GetBytes method converts basic data types to array of bytes.






      share|improve this answer























        0












        0








        0






        The BitConverter.GetBytes method converts basic data types to array of bytes.






        share|improve this answer












        The BitConverter.GetBytes method converts basic data types to array of bytes.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 15 at 7:57









        luci88filter

        787




        787



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246112%2fc-c-sharp-is-there-an-easy-way-to-reproduce-struct-casting-for-binary-communi%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo