结构体转换为字节数组中,用到微软的方法StructureToPtr,而如果结构体中变量为中文值的话,转换时失败,确定为中文占两字节,但是我不太知道应该怎样处理。代码如下
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Runtime.InteropServices; 6 7 namespace CharSizeDemo 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 class1 c1 = new class1(); 14 c1.s = "123456".PadRight(10).ToCharArray(); 15 var b1 = StructToBytes(c1); 16 class1 c2 = new class1(); 17 c2.s = "中文".PadRight(10).ToCharArray(); 18 var b2 = StructToBytes(c2); 19 } 20 21 public static byte[] StructToBytes(object obj) 22 { 23 int size = Marshal.SizeOf(obj); 24 IntPtr buffer = Marshal.AllocHGlobal(size); 25 try 26 { 27 Marshal.StructureToPtr(obj, buffer, false); 28 Byte[] bytes = new Byte[size]; 29 Marshal.Copy(buffer, bytes, 0, size); 30 return bytes; 31 } 32 finally 33 { 34 Marshal.FreeHGlobal(buffer); 35 } 36 } 37 } 38 39 [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] 40 public class class1 41 { 42 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] 43 public char[] s; 44 } 45 }
其中C2对象的变量S赋值中文,执行var b2 = StructToBytes(c2);时,会在StructureToPtr报错,意思是申请的空间不够。
求个方法
c2.s = Encoding.GB2312.GetBytes("中文").PadRight(10).ToCharArray();
Encoding获得中文的编码格式,参考楼上的没有问题。设置UTF-8也行!
/// <summary> /// 补齐字节到指定长度 /// </summary> /// <param name="strValue">待补齐字符串</param> /// <param name="nSpecifiedLen">指定的字节数组长度</param> /// <returns>指定长度的字节数组</returns> public static byte[] GetSpecifiedLenBytes(string strValue, Int32 nSpecifiedLen) { byte[] bValue = System.Text.Encoding.Unicode.GetBytes(strValue); if (bValue.Length < nSpecifiedLen) { byte[] bSpecifiedLenValue = new byte[nSpecifiedLen]; Array.Copy(bValue, 0, bSpecifiedLenValue, 0, bValue.Length); return bSpecifiedLenValue; } else { return bValue; } }