我将保存DataTable
到 *.dbf 文件 (dBase IV)。所以我有一个这样的结构:
[StructLayout(LayoutKind.Explicit, Pack = 1)]
public struct DbfHeader
{
[FieldOffset(0)]
private byte versionNumber;
[FieldOffset(1)]
private byte yearOfLastUpdate;
[FieldOffset(2)]
private byte monthOfLastUpdate;
[FieldOffset(3)]
private byte dayOfLastUpdate;
[FieldOffset(4)]
private Int32 numberOfRecords;
[FieldOffset(8)]
private Int16 lengthOfHeader;
[FieldOffset(10)]
private Int16 lengthOfEachRecord;
[FieldOffset(12)]
private Int16 reserved1;
[FieldOffset(14)]
private byte incompleteTransaction;
[FieldOffset(15)]
private byte encryptionFlag;
[FieldOffset(16)]
private byte[] freeRecordThread;
[FieldOffset(20)]
private byte[] reserved2;
[FieldOffset(28)]
private byte mdxFlag;
[FieldOffset(29)]
private byte languageDriver;
[FieldOffset(30)]
private Int16 reserved3;
public DbfHeader(int numberOfRecords, int numberOfFields, short recordLength, Encoding encoding)
{
// some code that initialize each field
}
}
另外,我有一种将DbfHeader
变量转换为byte[]
数组的方法,如下所示:
public static byte[] StructureToByteArray<T>(T structure)
{
int len = Marshal.SizeOf(structure);
byte[] result = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(structure, ptr, true);
Marshal.Copy(ptr, result, 0, len);
Marshal.FreeHGlobal(ptr);
return result;
}
但是这种方法行不通。在这Marshal.StructureToPtr(structure, ptr, true)
条线上,我得到了这个例外:
Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
有谁知道出了什么问题?任何帮助将不胜感激。