【问题标题】:Read an array of structs in C#在 C# 中读取结构数组
【发布时间】:2009-02-11 08:00:19
【问题描述】:

我见过here,并且还在谷歌上搜索“marshal”几种将字节数组转换为结构的方法。

但我正在寻找的是,是否有一种方法可以一步从文件中读取结构数组(好的,无论内存输入)?

我的意思是,从文件加载结构数组通常需要比 IO 时间更多的 CPU 时间(使用 BinaryReader 读取每个字段)。有什么解决办法吗?

我正在尝试尽快从文件中加载大约 400K 结构。

谢谢

巴勃罗

【问题讨论】:

  • 您是从一个大文件还是 400k 小文件中读取它们?如果你在一个文件中阅读所有内容,我认为应该很快

标签: c#


【解决方案1】:

您可能会感兴趣以下网址。

http://www.codeproject.com/KB/files/fastbinaryfileinput.aspx

否则我想到的伪代码如下:

一次性读取二进制数据并转换回结构..

public struct YourStruct
{ 
    public int First;
    public long Second;
    public double Third;
}

static unsafe byte[] YourStructToBytes( YourStruct s[], int arrayLen )
{
    byte[] arr = new byte[ sizeof(YourStruct) * arrayLen ];
    fixed( byte* parr = arr )
    { 
        * ( (YourStruct * )parr) = s; 
    }
    return arr;
}

static unsafe YourStruct[] BytesToYourStruct( byte[] arr, int arrayLen )
{
    if( arr.Length < (sizeof(YourStruct)*arrayLen) )
        throw new ArgumentException();
    YourStruct s[];
    fixed( byte* parr = arr )
    { 
        s = * ((YourStruct * )parr); 
    }
    return s;
}

现在您可以一次性从文件中读取 bytearray 并使用 BytesToYourStruct 转换回结构

希望你能实现这个想法并检查...

【讨论】:

  • 不幸的是,他们在这里“一个接一个”地这样做,这正是我想要避免的
  • 固定的解决方案似乎是我正在寻找的!谢谢!
  • 没有在 Mono 上编译:“无法将类型 'YourStruct[]' 隐式转换为 YourStruct”
【解决方案2】:

我在这个网站上找到了一个潜在的解决方案 - http://www.eggheadcafe.com/software/aspnet/32846931/writingreading-an-array.aspx

它基本上说像这样使用二进制格式化程序:

FileStream fs = new FileStream("DataFile.dat", FileMode.Create); BinaryFormatter 格式化程序 = new BinaryFormatter(); formatter.Serialize(fs, somestruct);

我还从这个网站上发现了两个问题 - Reading a C/C++ data structure in C# from a byte arrayHow to marshal an array of structs - (.Net/C# => C++)

我以前没有这样做过,我自己是一个 C# .NET 初学者。我希望这个解决方案有所帮助。

【讨论】:

  • 谢谢,但是与直接内存访问相比,“Serialize”速度较慢,其他链接使用“PtrToStructure”来“一个一个”地复制,这正是我想要避免的。
  • 抱歉,pablo,我昨天电脑出了点问题。所以我无法跟进。我不知道如何实现你想要的。祝一切顺利。
  • 希望你能发现。如果你这样做,请在此处发布答案。谢谢。
猜你喜欢
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多