代码之家  ›  专栏  ›  技术社区  ›  Pablo

读取c中的结构数组#

c#
  •  2
  • Pablo  · 技术社区  · 17 年前

    我见过 here ,还可以通过谷歌搜索“封送”将字节数组转换为结构的几种方法。

    但我要找的是,是否有一种方法可以一步从文件中读取结构数组(好吧,不管是什么内存输入)?

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

    我正试图从一个文件中尽快加载大约400K的结构。

    谢谢

    帕布洛

    2 回复  |  直到 14 年前
        1
  •  1
  •   Tetrad    14 年前

    以下网址可能是你感兴趣的。

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

    或者我认为伪代码如下:

    在一次快照中读取BinaryData并转换回结构..

    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转换回strucure

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

        2
  •  0
  •   Community Mohan Dere    9 年前

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

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

    filestream fs=new filestream(“datafile.dat”,filemode.create); binaryFormatter formatter=新的binaryFormatter(); 格式化程序。序列化(fs,somestruct);

    我也在这个网站上找到了两个问题- Reading a C/C++ data structure in C# from a byte array How to marshal an array of structs - (.Net/C# => C++)

    我以前没做过,我自己也是一个C.NET初学者。我希望这个解决方案有用。