Skip to main content
 首页 » 编程设计

c#之使用 char 数组编码异常

2024年02月23日14zdz8207

我有一些关于编码脚本的问题给出了异常。我有 C++ 结构,我试图在 C# 中模仿这些结构来测试我们拥有的系统。 C++ 结构如下所示:

#pragma pack(1) 
typedef struct 
{ 
  ACE_UINT32 result; 
  ACE_UINT32 command; 
  ACE_TCHAR information[2001]; 
  ACE_UINT16 informationLength; ///< Length of the variable information. 
} MsgStructType; 
#pragma pack() 

在 C# 中,我声明结构如下:

[StructLayout(LayoutKind.Explicit, Pack = 1)] 
struct MsgStruct 
{ 
  [FieldOffset(0)] 
  public uint result; 
  [FieldOffset(4)] 
  public uint command; 
  [FieldOffset(8)] 
  public Byte[] information; 
  [FieldOffset(2009)] 
  public ushort informationLength; 
} 

我使用以下方法对消息进行序列化和反序列化。

public static T DeserializeMsg<T>(Byte[] data) where T : struct 
{ 
  int objsize = Marshal.SizeOf(typeof(T)); 
  IntPtr buff = Marshal.AllocHGlobal(objsize); 
 
  Marshal.Copy(data, 0, buff, objsize); 
 
  T retStruct = (T)Marshal.PtrToStructure(buff, typeof(T)); 
 
  Marshal.FreeHGlobal(buff); 
 
  return retStruct; 
} 
 
public static Byte[] SerializeMessage<T>(T msg) where T : struct 
{ 
  int objsize = Marshal.SizeOf(typeof(T)); 
  Byte[] ret = new Byte[objsize]; 
 
  IntPtr buff = Marshal.AllocHGlobal(objsize); 
 
  Marshal.StructureToPtr(msg, buff, true); 
 
  Marshal.Copy(buff, ret, 0, objsize); 
 
  Marshal.FreeHGlobal(buff); 
 
  return ret; 
} 

我设法将消息序列化,通过 udp 将其发送到与接收到的相同的应用程序,并且数据大小似乎是正确的。我遇到的问题是当我尝试反序列化消息时。我收到以下错误代码:

也许使用 Byte[] 的方法不完整,但它与我用于序列化和反序列化数据的类完全相同。唯一的区别是我在两者之间通过 udp。

一些尝试和错误让我意识到 byte[] 或 char[] 的定义似乎是问题所在。

[StructLayout(LayoutKind.Explicit, Pack = 1)] 
struct MsgStruct 
{ 
  [FieldOffset(0)] 
  public uint result; 
  [FieldOffset(4)] 
  public uint command; 
  [FieldOffset(8)] 
//  public Byte[] information; 
//  [FieldOffset(2009)] 
  public ushort informationLength; 
} 

这个可以在系统之间毫无问题地传输。所以我猜它是我需要处理的字节/字符数组才能声明正确。

请您参考如下方法:

如果您只写 public Byte[] information;,它会被编码为一个指向数组的指针,但这不是您在这里拥有的。您需要做的是指定 [MarshalAs(UnmanagedType.ByValArray)],以便将其解释为直接位于结构中的数组:

[FieldOffset(8)] 
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2001)] 
public byte[] information; 

如果你这样做,我认为你将不再需要 LayoutKind.Explicit:

[StructLayout(LayoutKind.Sequential, Pack = 1)] 
struct MsgStruct 
{ 
    public uint result; 
    public uint command; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2001)] 
    public byte[] information; 
    public ushort informationLength; 
} 

编辑: information 数组必须恰好是声明的长度,即使您想放入少于那么多的字节。因此,对于您的示例,它可能看起来像这样:

var msg = new MsgStruct(); 
msg.information = new byte[2001]; 
var information = Encoding.ASCII.GetBytes("Kalle"); 
Array.Copy(information, msg.information, information.Length); 
var bytes = SerializeMessage(msg);