110,567
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StructToBytes(new Student() { name = new string[] { "123", "123", "123", "123", "123" }});
}
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct Student
{
public int number;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public String[] name;
}
public static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structObj, structPtr, false);
Marshal.Copy(structPtr, bytes, 0, size);
Marshal.FreeHGlobal(structPtr);
return bytes;
}
}
}