如何在C#中将字节复制到结构变量中? [英] How do I copy bytes into a struct variable in C#?
本文介绍了如何在C#中将字节复制到结构变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个struct abc
,我想将字节复制到struct变量中.与C/C ++中的memcpy类似.
我在套接字上收到了字节,它们是同一个struct abc
变量的字节.
I have a struct abc
and I want to copy bytes into a struct variable. Similar to memcpy in C/C++.
I receive the bytes over socket and they are the bytes of the same struct abc
variable.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct abc
{
public int a;
public int b;
public float c;
public char[] d; //30 size
}
推荐答案
您可以按如下所示将字节数组转换为您的结构:
You can convert the byte array to your structure as follows :
int size = Marshal.SizeOf(typeof(abc));
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
var struct = (abc)Marshal.PtrToStructure(ptr, typeof(abc));
Marshal.FreeHGlobal(ptr);
struct现在是您转换后的结构.请记住,尽管如此,注释(即字节顺序)
struct is now your converted structure. Bear in mind the comments that have been made about this though (i.e. byte ordering)
这篇关于如何在C#中将字节复制到结构变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文