首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用CopyMemory在VBA中存储数据并从内存映射文件中获取数据?

如何使用CopyMemory在VBA中存储数据并从内存映射文件中获取数据?
EN

Stack Overflow用户
提问于 2015-05-13 15:08:42
回答 1查看 5.9K关注 0票数 8

我正在尝试构建一个分布式计算系统,它使用内存映射文件来协调多台联网PC之间的工作,所有这些都是通过VBA实现的。换句话说,我想让一组联网的计算机同时在一个项目中以协调的方式工作,这个项目可以很容易地分成不同的部分。一台电脑需要13+时间来完成这个项目,这对我的客户来说是不现实的。

我想将信息存储在内存映射文件中,这将帮助PC以协调的方式在项目上工作(即不重复工作,避免竞争问题,等等)。我尝试过使用其他类型的文件来完成这一任务,这会导致文件争用问题或花费太长时间。因此,正如在这个论坛上所建议的,我正在尝试内存映射文件。

我对内存映射文件和分布式计算非常陌生。必须用VBA来完成。据我所知,我必须指定将该文件保存在我们网络上的一个目录中(这里是驱动器Z),所有PC都可以访问该目录。我拼凑了一些来自不同地方的代码:

代码语言:javascript
复制
Option Explicit

Private Const PAGE_READWRITE As Long = &H4
Private Const FILE_MAP_WRITE As Long = &H2
Private Const GENERIC_READ = &H80000000
Private Const GENERIC_WRITE = &H40000000
Private Const OPEN_ALWAYS = 4
Private Const FILE_ATTRIBUTE_NORMAL = &H80

Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, _
                                         ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, _
                                         ByVal lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, _
                                         ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long

Private Declare Function CreateFileMapping Lib "kernel32.dll" Alias "CreateFileMappingA" ( _
     ByVal hFile As Long, _
     ByVal lpFileMappigAttributes As Long, _
     ByVal flProtect As Long, _
     ByVal dwMaximumSizeHigh As Long, _
     ByVal dwMaximumSizeLow As Long, _
     ByVal lpName As String) As Long

Private Declare Function MapViewOfFile Lib "kernel32.dll" ( _
     ByVal hFileMappingObject As Long, _
     ByVal dwDesiredAccess As Long, _
     ByVal dwFileOffsetHigh As Long, _
     ByVal dwFileOffsetLow As Long, _
     ByVal dwNumberOfBytesToMap As Long) As Long

#If VBA7 Then
Public Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias _
    "RtlMoveMemory" (destination As Any, source As Any, _
    ByVal length As Long)
#Else
Public Declare Sub CopyMemory Lib "kernel32" Alias _
    "RtlMoveMemory" (destination As Any, source As Any, _
    ByVal length As Long)
    #End If

Private Declare Function UnmapViewOfFile Lib "kernel32.dll" ( _
     ByRef lpBaseAddress As Any) As Long

Private Declare Function CloseHandle Lib "kernel32.dll" ( _
     ByVal hObject As Long) As Long

Private hMMF As Long
Private pMemFile As Long

Sub IntoMemoryFileOutOfMemoryFile()

    Dim sFile As String
    Dim hFile As Long

    sFile = "Z:\path\test1.txt"

    hFile = CreateFile(sFile, GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)
    hMMF = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, 1000000, "MyMemoryMappedFile")

    pMemFile = MapViewOfFile(hMMF, FILE_MAP_WRITE, 0, 0, 0)

    Dim buffer As String

    buffer = "testing1"
    CopyMemory pMemFile, ByVal buffer, 128

    hMMF = CreateFileMapping(-1, 0, PAGE_READWRITE, 0, 1000000, "MyMemoryMappedFile")
    pMemFile = MapViewOfFile(hMMF, FILE_MAP_WRITE, 0, 0, 0)

     Dim buffer2 As String

    buffer2 = String$(128, vbNullChar)

     CopyMemory ByVal buffer2, pMemFile, 128

     MsgBox buffer2 & " < - it worked?"

     UnmapViewOfFile pMemFile
     CloseHandle hMMF
End Sub

例如,上面的代码尝试将字符串"testing1“放入文件test1.txt中,然后检索该字符串并将其存储在变量buffer2中,最后通过msgbox显示该字符串。超级简单。然而,我不知道自己在做什么。

我们所有的PC机都是64位的,Windows 7,Office/Excel 2013。

议题/问题:

  1. 运行IntoMemoryFileOutOfMemoryFile时,msgbox为空。
  2. 完成子之后,我打开test1.txt,得到:“进程无法访问文件,因为它正被另一个进程使用。”这表明我没有正确地使用UnmapViewOfFile和/或CloseHandle。
  3. 我想使这些内存文件持久,所以如果所有的PC被中断,我可以重新启动进程和拾音器,我停止了。

下面是一些我曾经在这里获得的链接:

有趣但不重要的信息:“项目”是针对对冲基金客户的。我是个金融界的人。我们每天对2000+ +股票进行1250+数据字段的分析,以作出宏观经济信号/预测来买卖股票、期货和期权。

更新:如果我分别更改以下两行CopyMemory (按值传递pMemFile ):

代码语言:javascript
复制
CopyMemory ByVal pMemFile, buffer, 128

还有..。

代码语言:javascript
复制
CopyMemory buffer2, ByVal pMemFile, 128

我在文件test1.txt和excel崩溃中得到了一堆疯狂的字符。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-14 23:57:07

对于第一个问题(还没有深入探讨),这与您如何将buffer传递给RtlMoveMemory有关。它期待一个指针,但您传递的是一个BSTR的副本。还请记住,VBA中的字符串是Unicode,因此您将得到互编空字符。我通常使用Byte数组或变体(它们将被编组成CSTR)。

对于第二个问题,文件将被锁定,因为您从未释放过hFile的句柄。实际上,一旦您将它传递给CreateFileMappingA,您就可以在hFile上调用CloseHandle

对于第三个问题,在进行第二个调用时,您正在重写句柄hMMF和指针pMemFile。理论上,它们应该返回相同的句柄和指针,就像您在同一个进程中一样,但是这并不能真正测试您是否得到了map视图。

至于内存访问,我可能建议将整个过程封装在一个类中,并将指针映射到比调用RtlMoveMemory更有用的东西。我将您在问题中链接的代码修改为一个类,使其更安全、更可靠、更方便使用(尽管它仍然需要通过错误检查来充实):

代码语言:javascript
复制
'Class MemoryMap
Option Explicit

Private Type SafeBound
    cElements As Long
    lLbound As Long
End Type

Private Type SafeArray
    cDim As Integer
    fFeature As Integer
    cbElements As Long
    cLocks As Long
    pvData As Long
    rgsabound As SafeBound
End Type

Private Const VT_BY_REF = &H4000&
Private Const FILE_ATTRIBUTE_NORMAL = &H80
Private Const OPEN_ALWAYS = &H4
Private Const GENERIC_READ = &H80000000
Private Const GENERIC_WRITE = &H40000000
Private Const PAGE_READWRITE = &H4
Private Const FILE_MAP_WRITE = &H2
Private Const FADF_FIXEDSIZE = &H10

Private cached As SafeArray
Private buffer() As Byte
Private hFileMap As Long
Private hMM As Long
Private mapped_file As String
Private bound As Long

Public Property Get FileName() As String
    FileName = mapped_file
End Property

Public Property Get length() As Long
    length = bound
End Property

Public Sub WriteData(inVal As String, offset As Long)
    Dim temp() As Byte
    temp = StrConv(inVal, vbFromUnicode)

    Dim index As Integer
    For index = 0 To UBound(temp)
        buffer(index + offset) = temp(index)
    Next index
End Sub

Public Function ReadData(offset, length) As String
    Dim temp() As Byte
    ReDim temp(length)

    Dim index As Integer
    For index = 0 To length - 1
        temp(index) = buffer(index + offset)
    Next index

    ReadData = StrConv(temp, vbUnicode)
End Function

Public Function OpenMapView(file_path As String, size As Long, mapName As String) As Boolean
    bound = size
    mapped_file = file_path

    Dim hFile As Long
    hFile = CreateFile(file_path, GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)
    hFileMap = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, size, mapName)
    CloseHandle hFile
    hMM = MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0)

    ReDim buffer(2)
    'Cache the original SafeArray structure to allow re-mapping for garbage collection.
    If Not ReadSafeArrayInfo(buffer, cached) Then
        'Something's wrong, close our handles.
        CloseOpenHandles
        Exit Function
    End If

    Dim temp As SafeArray
    If ReadSafeArrayInfo(buffer, temp) Then
        temp.cbElements = 1
        temp.rgsabound.cElements = size
        temp.fFeature = temp.fFeature And FADF_FIXEDSIZE
        temp.pvData = hMM
        OpenMapView = SwapArrayInfo(buffer, temp)
    End If    
End Function

Private Sub Class_Terminate()
    'Point the member array back to its own data for garbage collection.
    If UBound(buffer) = 2 Then
        SwapArrayInfo buffer, cached
    End If
    SwapArrayInfo buffer, cached
    CloseOpenHandles
End Sub

Private Sub CloseOpenHandles()
    If hMM > 0 Then UnmapViewOfFile hMM
    If hFileMap > 0 Then CloseHandle hFileMap
End Sub

Private Function GetBaseAddress(vb_array As Variant) As Long
    Dim vtype As Integer
    'First 2 bytes are the VARENUM.
    CopyMemory vtype, vb_array, 2
    Dim lp As Long
    'Get the data pointer.
    CopyMemory lp, ByVal VarPtr(vb_array) + 8, 4
    'Make sure the VARENUM is a pointer.
    If (vtype And VT_BY_REF) <> 0 Then
        'Dereference it for the actual data address.
        CopyMemory lp, ByVal lp, 4
        GetBaseAddress = lp
    End If
End Function

Private Function ReadSafeArrayInfo(vb_array As Variant, com_array As SafeArray) As Boolean
    If Not IsArray(vb_array) Then Exit Function

    Dim lp As Long
    lp = GetBaseAddress(vb_array)
    If lp > 0 Then
        With com_array
            'Copy it over the passed structure
            CopyMemory .cDim, ByVal lp, 16
            'Currently doesn't support multi-dimensional arrays.
            If .cDim = 1 Then
                CopyMemory .rgsabound, ByVal lp + 16, LenB(.rgsabound)
                ReadSafeArrayInfo = True
            End If
        End With
    End If
End Function

Private Function SwapArrayInfo(vb_array As Variant, com_array As SafeArray) As Boolean
    If Not IsArray(vb_array) Then Exit Function
    Dim lp As Long
    lp = GetBaseAddress(vb_array)

    With com_array
        'Overwrite the passed array with the SafeArray structure.
        CopyMemory ByVal lp, .cDim, 16
        If .cDim = 1 Then
            CopyMemory ByVal lp + 16, .rgsabound, LenB(.rgsabound)
            SwapArrayInfo = True
        End If
    End With    
End Function

用法如下:

代码语言:javascript
复制
Private Sub MMTest()
    Dim mm As MemoryMap

    Set mm = New MemoryMap
    If mm.OpenMapView("C:\Dev\test.txt", 1000, "TestMM") Then
        mm.WriteData "testing1", 0
        Debug.Print mm.ReadData(0, 8)
    End If

    Set mm = Nothing
End Sub

您还需要以下声明:

代码语言:javascript
复制
Public Declare Function MapViewOfFile Lib "kernel32.dll" ( _
    ByVal hFileMappingObject As Long, _
    ByVal dwDesiredAccess As Long, _
    ByVal dwFileOffsetHigh As Long, _
    ByVal dwFileOffsetLow As Long, _
    ByVal dwNumberOfBytesToMap As Long) As Long

Public Declare Sub CopyMemory Lib "kernel32" Alias _
    "RtlMoveMemory" (Destination As Any, Source As Any, _
    ByVal length As Long)

Public Declare Function CloseHandle Lib "kernel32.dll" ( _
    ByVal hObject As Long) As Long

Public Declare Function UnmapViewOfFile Lib "kernel32.dll" ( _
    ByVal lpBaseAddress As Any) As Long

另外要记住的一点是,由于您使用的是网络驱动器,所以您需要确保缓存机制不会干扰对文件的访问。具体来说,您需要确保所有客户端都关闭了网络文件缓存。您还可能希望确定地刷新内存映射,而不是依赖于操作系统(请参阅FlushViewOfFile)。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30218821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档