首页 新闻 会员 周边

C# 结构体转字节数组的问题

0
悬赏园豆:20 [已解决问题] 解决于 2015-02-04 19:51

结构体转换为字节数组中,用到微软的方法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报错,意思是申请的空间不够。

求个方法

diorlv2010的主页 diorlv2010 | 初学一级 | 园豆:188
提问于:2014-11-28 13:25
< >
分享
最佳答案
0

c2.s = Encoding.GB2312.GetBytes("中文").PadRight(10).ToCharArray();

收获园豆:15
Launcher | 高人七级 |园豆:45045 | 2014-11-28 14:58
其他回答(2)
0

Encoding获得中文的编码格式,参考楼上的没有问题。设置UTF-8也行!

收获园豆:5
Mr.Brian | 园豆:1518 (小虾三级) | 2014-11-29 11:05
0
        /// <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;
            }
        }
diorlv2010 | 园豆:188 (初学一级) | 2015-02-04 19:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册