我想將一個結構序列化爲磁盤作爲原始字節。這是它的(簡化)版本。將結構編組爲字節數組僅適用於單個字節?
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class TestData :BaseStructure
{
public byte[] bytes = new byte[]{65,66,67}; // this doesn't write ABC as expected
}
甲write
函數使用ConvertStructureToBytes
方法將其轉換爲一個字節數組和一個二進制作家然後將其寫入。
public void Write(BaseStructure baseStructure)
{
binaryWriter.Write(ConvertStructureToBytes(baseStructure));
}
的ConvertStructureToBytes
部分
public byte[] ConvertStructureToBytes(BaseStructure baseStructure)
{
int len = Marshal.SizeOf(baseStructure);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(baseStructure, ptr,false);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
如果我更換字節線
public byte byte = 65; // This now writes an A , as expected
我已經試過
public byte[] bytes = Encoding.ASCII.GetBytes("ABC"); //doesn't work either
這可能有事情做與ConvertStructureToBytes
函數,它不應該像處理字節數組一樣。
我需要做些什麼才能成功寫出'ABC'?
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2014-09-12 21:04:25
什麼是BaseStructure?你的'TestData'類繼承了它,但是你沒有序列化一個'TestData'實例,而是一個'BaseStructure'實例,它不知道'TestData'類中聲明的數據。 – Guffa 2014-09-12 21:10:32