This structure:

struct struct_1 { public static byte __TYPE; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string string_1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)] public string string_2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string string_3; // тут например "1234567890abcdef" public byte GetTypeStruct() { return __TYPE; } } 

I pass to this function:

 public static byte[] getBytes(T str) { int size = Marshal.SizeOf(str); byte[] arr = new byte[size+1]; IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(str, ptr, true); Marshal.Copy(ptr, arr, 1, size); Marshal.FreeHGlobal(ptr); arr[0] = str.GetTypeStruct(); return arr; } 

The arr array is always returned with a zero byte in the last element, i.e. during the reverse conversion, string_3 receives not " 1234567890abcdef ", but " 1234567890abcde ". The change in the number of elements helped:

 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 17)] public string string_3; 

But the problem is probably not the case.

  • one
    Quote from MSDN : The ByValTStr type is used for embedded fixed-length character arrays located in a structure. Other types apply to string references included in structures containing pointers to strings. You do not have an array, but a string. - Alexander Petrov
  • Use char array instead of string if such conversion rules (ASCIIZ) do not suit you. - nick_n_a

0