簡體   English   中英

讀取C#中的結構數組

[英]Read an array of structs in C#

我在這里看到 ,並且還在搜索“元帥”以幾種方式將字節數組轉換為結構。

但是我正在尋找的是是否有一種方法可以一步一步地從文件中讀取結構數組(好了,無論是什么內存輸入)?

我的意思是,從文件加載結構數組通常比IO時間花費更多的CPU時間(使用BinaryReader讀取每個字段)。 有什么解決方法嗎?

我試圖從文件中盡快加載大約40萬個結構。

謝謝

巴勃羅

以下網址可能會讓您感興趣。

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

否則我會想到如下的偽代碼:

一次讀取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;
}

現在,您可以一次性從文件中讀取字節數組,並使用BytesToYourStruct轉換回結構

希望您能實現這個想法並檢查...

我在此站點上找到了潛在的解決方案-http: //www.eggheadcafe.com/software/aspnet/32846931/writingreading-an-array.aspx

它說基本上像​​這樣使用Binary Formatter:

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

我還從該站點發現了兩個問題- 從字節數組中讀取C#中的C / C ++數據結構,以及如何編組結構數組-(.Net / C#=> C ++)

我以前從未做過此事,我本人還是C#.NET初學者。 希望此解決方案有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM