怎样byte数组中的内容复制到一个自定义结构中?
我是刚刚接触c#的,想请教一下如何将一个结构体中的数据整体赋值给一个数组。
下面是我定义的结构体;
public struct myStr
{
public Byte bt1; //协议版本号设置为1
public Byte bt2;
public short st1; //消息来源
public Byte bt3; //消息长度
}
这是定义的数组
public static byte[] PubSendBuffer;
PubSendBuffer = ……;//在数据库中读取
在C++中可以这样用memcpy方法,Array.copy也是类似的功能吧。可是C#中没有memcpy函数呀?我怎么才能实现呢?
--------------------编程问答-------------------- BitConverter 类 将基础数据类型与字节数组相互转换。
去看MSDN... --------------------编程问答-------------------- 参考如下代码:
[StructLayout(LayoutKind.Sequential, Pack = 1)] // 这采用对齐方式,楼主根据情况而定。
public struct myStr
{
public Byte bt1; //协议版本号设置为1
public Byte bt2;
public short st1; //消息来源
public Byte bt3; //消息长度
}
public static byte[] PubSendBuffer;
static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structObj, buffer, false);
byte[] bytes = new byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
static object BytesToStruct(byte[] bytes, Type strcutType)
{
int size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
private void button2_Click(object sender, EventArgs e)
{
myStr m = new myStr();
m.bt1 = 0x01;
m.bt2 = 0x02;
m.st1 = 0x0403;
m.bt3 = 0x05;
byte[] buffer = StructToBytes(m);
Console.WriteLine(BitConverter.ToString(buffer)); //01-02-03-04-05
}
--------------------编程问答-------------------- 用API拷贝内存也可。
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
public static extern void CopyMemory(byte[] pDst, ref myStr pSrc, int ByteLen);
private void button2_Click(object sender, EventArgs e)
{
myStr m = new myStr();
m.bt1 = 0x01;
m.bt2 = 0x02;
m.st1 = 0x0403;
m.bt3 = 0x05;
byte[] buffer = new byte[Marshal.SizeOf(typeof(myStr))];
CopyMemory(buffer, ref m, buffer.Length);
Console.WriteLine(BitConverter.ToString(buffer)); //01-02-03-04-05
}
--------------------编程问答-------------------- ^ō^ zswang 总是很快手... --------------------编程问答-------------------- static object BytesToStruct(byte[] bytes, Type strcutType)
这个怎么用啊,请给个例子,谢谢。 --------------------编程问答-------------------- c#有Buffer.Copy
--------------------编程问答--------------------
早起的虫儿被鸟吃
myStr m = new myStr();
m.bt1 = 0x01;
m.bt2 = 0x02;
m.st1 = 0x0403;
m.bt3 = 0x05;
byte[] buffer = StructToBytes(m);
myStr n = (myStr)BytesToStruct(buffer, typeof(myStr));
Console.WriteLine("{0:X2},{1:X2},{2:X4},{3:X2}", n.bt1, n.bt2, n.st1, n.bt3);
补充:.NET技术 , C#