Array backed by memory mapped file
The memory for an array is allocated from a memory mapped file. This is an big advantage for huge arrays, as they will not fill the pagefile.
AI
Ringkasan AI: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.
Kode Sumber
Private Type SAFEARRAYBOUND
cElements As Long
lLbound As Long
End Type
Private Type SAFEARRAY2D
cDims As Integer
fFeatures As Integer
cbElements As Long
cLocks As Long
pvData As Long
Bounds(0 To 1) As SAFEARRAYBOUND
End Type
' keep it safe, be global
Dim mArray() As Double
Dim tSA As SAFEARRAY2D
Dim hFile As Long
Dim hFileMapping As Long
Dim lpFileBase As Long
Sub Create2DMMArray(Filename As String, ElemSize As Long, n As Long, m As Long)
With tSA
.cbElements = ElemSize
.cDims = 2
.Bounds(0).lLbound = 0
.Bounds(0).cElements = m
.Bounds(1).lLbound = 0
.Bounds(1).cElements = n
.fFeatures = &H10 Or &H2 ' FADF_FIXEDSIZE and FADF_STATIC
.cLocks = 1
GetViewOfFile Filename, ElemSize, n, m
.pvData = lpFileBase
End With
If tSA.pvData = 0 Then
Err.Raise 1243, "Create2DMMArray()", "Memory mapping failed"
Else
CopyMemory ByVal VarPtrArray(mArray()), VarPtr(tSA), 4
End If
End Sub
Function GetViewOfFile(Filename As String, ElemSize As Long, n As Long, m As Long) As Long
hFile = CreateFile(Filename, GENERIC_READ Or GENERIC_WRITE, 0, 0, _
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, vbEmpty)
If hFile = -1 Then Err.Raise Err.LastDllError, "GetViewOfFile()", "Could not open file " & Filename
Dim FileSize As Long
FileSize = ElemSize * m * n
hFileMapping = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, FileSize, vbEmpty)
lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0 * FileSize)
GetViewOfFile = lpFileBase
End Function
Function FreeViewOfFile() As Long
Dim ret As Long
' Clear the temporary array descriptor
' This may be necessary under NT4.
CopyMemory ByVal VarPtrArray(mArray), 0&, 4
FreeViewOfFile = UnmapViewOfFile(lpFileBase)
If FreeViewOfFile = 0 Then Debug.Print "Error: ", Err.LastDllError
' If FreeViewOfFile = 0 Then Err.Raise Err.LastDllError, "FreeViewOfFile()", "Memory unmapping failed"
ret = CloseHandle(hFileMapping)
ret = CloseHandle(hFile)
End Function
Function checkMMA()
Dim n As Long, m As Long, i As Long, j As Long
Dim Filename As String, ElemSize As Long
Filename = "c:\kill.me"
n = 10 ^ 6: m = 10
ElemSize = 8 ' size of Double is 8
'Create 2D Array(m,n) of Double,
Create2DMMArray Filename, ElemSize, n, m
'random acess to our file
For i = 0 To 1000
mArray(Rnd * n Mod n, Rnd * m Mod m) = i
Next i
' close down, destroy array
' this MUST be called
FreeViewOfFile
End Function
Komentar Asli (3)
Dipulihkan dari Wayback Machine