C#-将字节数组转换为struct数组,反之亦然(反向) [英] C# - Cast a byte array to an array of struct and vice-versa (reverse)

查看:141
本文介绍了C#-将字节数组转换为struct数组,反之亦然(反向)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Color []保存到文件中.为此,我发现使用"System.IO.File.WriteAllBytes"将字节数组保存到文件中应该非常有效.

I would like to save a Color[] to a file. To do so, I found that saving a byte array to a file using "System.IO.File.WriteAllBytes" should be very efficient.

考虑到以下因素,我想将我的Color [](结构体数组)转换为字节数组以一种安全的方式:

I would like to cast my Color[] (array of struct) to a byte array into a safe way considering:

  • 小尾数/大尾数的潜在问题(我想不可能发生,但想确定)
  • 具有2个指向相同存储器的,不同类型的指针.垃圾回收是否知道该怎么做-移动对象-删除指针???

如果有可能,最好有一种通用的方法来将字节数组转换为任何结构(T结构)的数组,反之亦然.

If it is possible, it would be nice to have a generic way to cast array of byte to array of any struct (T struct) and vice-versa.

如果不可能,为什么?

谢谢, 埃里克

我认为这2个解决方案会产生一个我要避免的副本,并且它们都使用了Marshal.PtrToStructure,它特定于结构而不是结构数组:

I think that those 2 solutions make a copy that I would like to avoid and also they both uses Marshal.PtrToStructure which is specific to structure and not to array of structure:

  • Reading a C/C++ data structure in C# from a byte array
  • How to convert a structure to a byte array in C#?

推荐答案

关于数组类型转换

作为一种语言,C#故意使将对象或数组扁平化为字节数组的过程变得困难,因为这种方法与.NET强类型化的原则背道而驰.常规的替代方法包括一些序列化工具,这些工具通常被认为更安全,更健壮,或者是手动序列化编码,例如BinaryWriter.

C# as a language intentionally makes the process of flattening objects or arrays into byte arrays difficult because this approach goes against the principals of .NET strong typing. The conventional alternatives include several serialization tools which are generally seen a safer and more robust, or manual serialization coding such as BinaryWriter.

只有当变量的类型可以隐式或显式转换时,才可以执行具有不同类型的两个变量指向内存中的同一对象的操作.从一种元素类型的数组转换为另一种元素并不是一件容易的事:它必须转换跟踪诸如数组长度等内容的内部成员.

Having two variables of different types point to the same object in memory can only be performed if the types of the variables can be cast, implicitly or explicitly. Casting from an array of one element type to another is no trivial task: it would have to convert the internal members that keep track of things such as array length, etc.

一种简单的读写Color []到文件的方法

void WriteColorsToFile(string path, Color[] colors)
{
    BinaryWriter writer = new BinaryWriter(File.OpenWrite(path));

    writer.Write(colors.Length);

    foreach(Color color in colors)
    {
        writer.Write(color.ToArgb());
    }

    writer.Close();
}

Color[] ReadColorsFromFile(string path)
{
    BinaryReader reader = new BinaryReader(File.OpenRead(path));

    int length = reader.ReadInt32();

    Colors[] result = new Colors[length];

    for(int n=0; n<length; n++)
    {
        result[n] = Color.FromArgb(reader.ReadInt32());
    }

    reader.Close();
}

这篇关于C#-将字节数组转换为struct数组,反之亦然(反向)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆