using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices; //需要添加命名空间
namespace YuanLiChenXiao
{
/// <summary>
/// 消息头结构体
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
public struct StructMessage
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)]
public byte[] fileName; //文件名30个byte
public long fileLength; //文件长度8byte
}
public class ConverData
{
/// <summary>
/// 将结构体转换成byte
/// </summary>
/// <param name="obj">结构体</param>
/// <returns>byte数组</returns>
public static byte[] StructToByte(object obj)
{
if (null == obj)
{
return null;
}
//长度
int len = Marshal.SizeOf(obj);
byte[]buffer = new byte[len];
//从进程非托管内存中分配内存
IntPtr ptr = Marshal.AllocHGlobal(len);
//将数据从托管的对象封送到非托管内存
Marshal.StructureToPtr(obj, ptr, true);
//将数据从非托管的内存指针复制到托管
Marshal.Copy(ptr, buffer, 0, len);
//释放分配的内存
Marshal.FreeHGlobal(ptr);
return buffer;
}
/// <summary>
/// 将byte[]还原成结构体
/// </summary>
/// <param name="buffer">byte[]</param>
/// <param name="type"></param>
/// <returns></returns>
public static object ByteToStruct(byte[] buffer, Type type)
{
int len = Marshal.SizeOf(type);
if (len != buffer.Length)
{
return null;
}
IntPtr ptr = Marshal.AllocHGlobal(len);
//将托管数据复制到非托管内存
Marshal.Copy(buffer, 0, ptr, len);
object obj = Marshal.PtrToStructure(ptr, type);
//释放内存
Marshal.FreeHGlobal(ptr);
return obj;
}
/// <summary>
/// 调用
/// </summary>
public void UseExample()
{
//赋值
StructMessage header = new StructMessage();
header.fileLength = 9527;
string fileName = "YuanLiChenXiao.exe";
header.fileName = new byte[30];
byte[] tmp = Encoding.UTF8.GetBytes(fileName);
header.fileName = Array.Copy(tmp,header.fileName,30);
//转换为定长38字节
byte[] buffer = ConverData.StructToByte(header);
//还原结构体
StructMessage msg = (StructMessage)ConverData.ByteToStruct(buffer, typeof(StructMessage));
}
}
}