Because the program must communicate with the program developed by C ++, the communication data is the converted byte stream of the struct, therefore, C # Must be able to smoothly convert bytes into C # struct.
- Define the C # struct corresponding to C ++
Code
// C ++ struct
Struct tagCheakUser
{
Char userName [12];
Char pwd [32];
}
// Corresponding C # struct
[StructLayout (LayoutKind. Sequential, Pack = 1)]
Public struct CheckUser
{
[Financialas (UnmanagedType. ByValTStr, SizeConst = 12)]
Public string userName;
[Financialas (UnmanagedType. ByValTStr, SizeConst = 32)]
Public string pwd;
}
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.
- Mutual conversion between struct and byte []
Code
//convert structure T to byte[]
public static byte[] ConvertStructToBytes(object objStruct)
{
//get the size of structure
int size = Marshal.SizeOf(objStruct);
//define buffer arrays
byte[] buffer = new byte[size];
//Alloc unmanaged memory and Copy structure to unmanaged memory
IntPtr ipStruct = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(objStruct, ipStruct, false);
//Copy to the byte array
Marshal.Copy(ipStruct, buffer, 0, size);
//Free unmanaged memory
Marshal.FreeHGlobal(ipStruct);
return buffer;
}
//convert byte array to sturcture
public static TR ConvertBytesToSturct<TR>(byte[] datas)
{
//get size of sturcture
int size = Marshal.SizeOf(typeof(TR));
//can not be convert
if (datas.Length < size)
{
return