簡體   English   中英

從文件中讀取非字節數組而不必使用循環?

[英]Read non-byte array from file without having to use a loop?

有沒有辦法將二進制數據從文件讀取到像 C 這樣的數組中,我可以將任何類型的指針傳遞給 i/o 函數? 我正在考慮像 BinaryReader::ReadBytes() 之類的東西,但這會返回一個字節 [],我無法將其轉換為所需的數組指針類型。

如果你有一個固定大小的struct

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct MyFixedStruct
{
  //..
}

然后,您可以使用以下命令在一個 go 中讀取它:

public static T ReadStruct<T>(Stream stream)
{
    byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
    stream.Read(buffer, 0, Marshal.SizeOf(typeof(T)));
    GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return typedStruct;
}

這會讀入一個覆蓋struct大小的字節數組,然后將字節數組編組到結構中。 你可以像這樣使用它:

MyFixedStruct fixedStruct =  ReadStruct<MyFixedStruct>(stream);

只要指定了數組長度,該struct就可以包含數組類型,即:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MyFixedStruct
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
    public int[] someInts; // 5 int's
    //..
};

編輯:

我看到您只想讀取一個short數組 - 在這種情況下,只需讀取字節數組並使用Buffer.BlockCopy()轉換為您想要的數組:

byte[] someBytes = ..
short[] someShorts = new short[someBytes.Length/2];
Buffer.BlockCopy(someBytes, 0, someShorts, 0, someBytes.Length);

這是相當有效的,相當於引擎蓋下 C++ 中的memcpy 當然,您唯一的其他開銷是原始字節數組將被分配並隨后被垃圾收集。 這種方法也適用於任何其他原始數組類型。

如何將結構的序列化數組存儲在文件中? 您可以輕松構建結構數組。 不確定如何通過文件 stream,就像在 C 中所做的那樣。

使用 Stream Class 怎么樣,因為它提供了字節序列的通用視圖。

暫無
暫無

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

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