1. Define the C # struct corresponding to C ++
Struct in C # cannot define pointers, character arrays, and can only define references to character arrays.
C ++The message structure of is as follows:
// Message format: 4 + 16 + 4 + 4 = 28 bytes
Struct cs_message {
U32_t pai_type;
Char username [16];
U32_t dstid;
U32_t srcid;
};
C #The struct is defined as follows:
[Structlayout (layoutkind. Sequential, pack = 1)]
Public struct my_message
{
Public uint32 pai_type;
[Financialas (unmanagedtype. byvaltstr, sizeconst = 16)]
Public String username;
Public uint32 dstid;
Public uint32 srcid;
Public my_message (string S)
{
Required _type = 0;
Username = s;
Dstid = 0;
Srcid = 0;
}
}
In the header file definition of C ++, # pragma Pack 1 bytes are aligned by 1, so the structure of C # must also be added with the corresponding features, layoutkind. the sequential attribute layout the struct in sequence when exported to the unmanaged memory. For the char array type of C ++, string can be directly used in C #. Of course, you must also add the characteristics and length constraints of the mail. 2. Mutual conversion between struct and byte []
Define a class with two methods for mutual conversion:
Public class Converter
{
Public byte [] structtobytes (object structure)
{
Int32 size = marshal. sizeof (structure );
Console. writeline (size );
Intptr buffer = marshal. allochglobal (size );
Try
{
Marshal. structuretoptr (structure, buffer, false );
Byte [] bytes = new byte [size];
Marshal. Copy (buffer, bytes, 0, size );
Return bytes;
}
Finally
{
Marshal. freehglobal (buffer );
}
}
Public object bytestostruct (byte [] bytes, type strcuttype)
{
Int32 size = marshal. sizeof (strcuttype );
Intptr buffer = marshal. allochglobal (size );
Try
{
Marshal. Copy (bytes, 0, buffer, size );
Return marshal. ptrtostructure (buffer, strcuttype );
}
Finally
{
Marshal. freehglobal (buffer );
}
}
} 3. Test results:
Static void main (string [] ARGs)
{
// Define an object of the conversion class and initialize it
Converter convert = new converter ();
// Define the message structure
My_message m;
// Initialize the message structure
M = new my_message ("yanlina ");
M. ipv_type = 1633837924;
M. srcid = 1633837924;
M. dstid = 1633837924;
// Use the structtobytes method of the object of the conversion class to convert the M struct to a byte
Byte [] Message = convert. structtobytes (m );
// Use the bytestostruct method of the object of the conversion class to convert byte to M struct.
My_message n = (my_message) convert. bytestostruct (message, M. GetType ());
// Output test
Console. writeline (encoding. ASCII. getstring (Message ));
Console. writeline (N. username );
}
The size of the struct is the same as that of the C ++ struct. At the same time, the struct and byte Arrays can be converted to each other to facilitate UDP sending and receiving.