[英]How to convert Struct Array to Byte Array in c#?
It is easy to convert primitive types to bytes by using Buffer.BlockCopy(). 使用Buffer.BlockCopy()可以很容易地将原始类型转换为字节。
But if I have a array of DateTime, which function should I use to convert the DateTime[] to byte[]? 但是,如果我有一个DateTime数组,应该使用哪个函数将DateTime []转换为byte []?
If I have a constant size of struct (which means I can use Marshal to convert struct to byte[]), which way should I use to convert the T[](struct array) to byte[]? 如果我的结构大小恒定(这意味着我可以使用Marshal将结构转换为byte []),应该使用哪种方式将T [](结构数组)转换为byte []?
If you are after a copy of the underlying in-memory representation, then one approach is to just access the data unsafe
- something like: 如果您正在寻找底层内存表示形式的副本,那么一种方法是仅访问unsafe
的数据-类似于:
// invent some data
DateTime[] original = new DateTime[10];
for (int i = 0; i < original.Length; i++)
original[i] = new DateTime(2014, 1, i + 1);
byte[] blob = new byte[original.Length * sizeof(DateTime)];
fixed (DateTime* src = original)
fixed (byte* dest = blob)
{
DateTime* typedDest = (DateTime*)dest;
for(int i = 0; i < original.Length; i++)
{
typedDest[i] = src[i];
}
}
However, this is hugely dependent upon what you expect the contents of the byte[]
to be afterwards, and what you intend doing with it. 然而,这是巨大的取决于你所期望的内容byte[]
要算账,你打算用它做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.