简体   繁体   English

读取C#中的结构数组

[英]Read an array of structs in C#

I've seen here , and also googling for "marshal" several ways to convert a byte array to a struct. 我在这里看到 ,并且还在搜索“元帅”以几种方式将字节数组转换为结构。

But what I'm looking for is if there is a way to read an array of structs from a file (ok, whatever memory input) in one step? 但是我正在寻找的是是否有一种方法可以一步一步地从文件中读取结构数组(好了,无论是什么内存输入)?

I mean, load an array of structs from file normally takes more CPU time (a read per field using a BinaryReader) than IO time. 我的意思是,从文件加载结构数组通常比IO时间花费更多的CPU时间(使用BinaryReader读取每个字段)。 Is there any workaround? 有什么解决方法吗?

I'm trying to load about 400K structs from a file as fast as possible. 我试图从文件中尽快加载大约40万个结构。

Thanks 谢谢

pablo 巴勃罗

Following URL may be of interest to you. 以下网址可能会让您感兴趣。

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

Or otherwise I think of pseudo code like the following: 否则我会想到如下的伪代码:

readbinarydata in a single shot and convert back to structure.. 一次读取readbinarydata并转换回结构。

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;
}

Now you can read bytearray from the file in a single shot and convert back to strucure using BytesToYourStruct 现在,您可以一次性从文件中读取字节数组,并使用BytesToYourStruct转换回结构

Hope you can implement this idea and check... 希望您能实现这个想法并检查...

I found a potential solution at this site - http://www.eggheadcafe.com/software/aspnet/32846931/writingreading-an-array.aspx 我在此站点上找到了潜在的解决方案-http: //www.eggheadcafe.com/software/aspnet/32846931/writingreading-an-array.aspx

It says basically to use Binary Formatter like this: 它说基本上像​​这样使用Binary Formatter:

FileStream fs = new FileStream("DataFile.dat", FileMode.Create); FileStream fs = new FileStream(“ DataFile.dat”,FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, somestruct); formatter.Serialize(fs,somestruct);

I also found two questions from this site - Reading a C/C++ data structure in C# from a byte array and How to marshal an array of structs - (.Net/C# => C++) 我还从该站点发现了两个问题- 从字节数组中读取C#中的C / C ++数据结构,以及如何编组结构数组-(.Net / C#=> C ++)

I haven't done this before, being a C# .NET beginner myself. 我以前从未做过此事,我本人还是C#.NET初学者。 I hope this solution helps. 希望此解决方案有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM