【发布时间】:2014-09-01 13:49:15
【问题描述】:
我尝试过使用 BinaryReader,但这绝对行不通。在第一个 reader.Readx 位时,它几乎塞满了。
所以,我改变了策略并尝试使用 FILEOPEN、FILEGETOBJECT、FILEPUTOBJECT。
这适用于第一个“记录”,但从那时起,我得到了
“试图读取或写入受保护的内存。这通常表明其他内存已损坏”
这是目前为止的代码:
Dim iFreeFile As Integer = FreeFile()
Dim iFileLength As Integer
' open the file
iFreeFile = FreeFile()
FileOpen(iFreeFile, inFilePath, OpenMode.Binary, OpenAccess.Read, OpenShare.Default)
iFileLength = FileLen(inFilePath)
' This bit reads the data
Dim recordLength As Integer = Marshal.SizeOf(outValue)
Dim myBytes As Byte() : ReDim myBytes(recordLength)
FileGet(iFreeFile, myBytes, inRecordCount)
BuildStr(myBytes, outValue.GetType, outValue)
inRecordCount += 1
outValue 是几个结构体之一
''' <summary>
''' ' Marshal the Byte Array to the Structure
''' </summary>
''' <param name="Buff">Array of Bytes</param>
''' <param name="MyType">Type of the Structure</param>
''' <param name="outBuffer">Structure Object</param>
Private Sub BuildStr(ByVal Buff() As Byte,
ByVal MyType As System.Type,
ByRef outBuffer As Object)
' Marshal the Byte Array to the Structure
Dim MyGC As GCHandle = GCHandle.Alloc(Buff, GCHandleType.Pinned)
'Marshals data from an unmanaged block of memory
'to a newly allocated managed object of the specified type.
outBuffer = Marshal.PtrToStructure(MyGC.AddrOfPinnedObject, MyType) ' <----- here we get the error
End Sub
myBytes 数组可以从 FileGet 指令正常加载。 outValue 通过 ByRef 传递。
什么可能导致这个错误?
昨晚我在想,每次读取记录时是否必须关闭并重新打开文件?
【问题讨论】:
标签: arrays vb.net structure binaryfiles