创建和读取内存映像文件

Module mdlAPI

    Public Declare Function CreateFileMapping Lib "kernel32" _

        Alias "CreateFileMappingA" (ByVal hFile As IntPtr, _

        ByRef lpFileMappigAttributes As IntPtr, _

        ByVal flProtect As IntPtr, ByVal dwMaximumSizeHigh As IntPtr, _

        ByVal dwMaximumSizeLow As IntPtr, ByVal lpName As String) As IntPtr

 

    Public Declare Function OpenFileMapping Lib "kernel32" _

        Alias "OpenFileMappingA" (ByVal dwDesiredAccess As IntPtr, _

        ByVal bInheritHandle As IntPtr, ByVal lpName As String) As IntPtr

 

    Public Declare Function MapViewOfFile Lib "kernel32" _

        Alias "MapViewOfFile" (ByVal hFileMappingObject As IntPtr, _

        ByVal dwDesiredAccess As IntPtr, ByVal dwFileOffsetHigh As IntPtr, _

        ByVal dwFileOffsetLow As IntPtr, ByVal dwNumberOfBytesToMap As IntPtr) As IntPtr

 

    Public Declare Function UnmapViewOfFile Lib "kernel32" _

        Alias "UnmapViewOfFile" (ByVal lpBaseAddress As IntPtr) As IntPtr

 

    Public Declare Function CloseHandle Lib "kernel32" _

        Alias "CloseHandle" (ByVal hObject As IntPtr) As IntPtr

 

    Public Declare Sub CopyMemory Lib "kernel32" _

        Alias "RtlMoveMemory" (ByVal pDst As IntPtr, _

        ByVal pSrc As IntPtr, ByVal ByteLen As Integer)

 

    Public Declare Function GetLastError Lib "kernel32" () As IntPtr

    Public Const Read_Write = &H4

End Module


 

    Private Sub 写入映像()

        Dim hMF As Integer = CreateFileMapping(&HFFFFFFFF, 0, Read_Write, 0, 1024, TextBox1.Text)

        If hMF = 0 Then MessageBox.Show(GetLastError, "创建失败") : Return

 

        Dim hMV As IntPtr = MapViewOfFile(hMF, 2, 0, 0, 0)

 

        If hMV = 0 Then MessageBox.Show(GetLastError, "映射失败") : Return

 

        Dim content As String = TextBox2.Text

        Dim ptr As IntPtr = Marshal.StringToHGlobalAuto(content)

        CopyMemory(hMV, ptr, content.Length)

        MessageBox.Show("测试期间,不要点确定!" & vbNewLine & _

            "点确定后内存映射文件自动被撤销!", "内存映射文件创建成功!")

 

        UnmapViewOfFile(hMV)

        CloseHandle(hMF)

    End Sub

 

 

 

 


 

 

 

 

    Private Sub 读取映像()

        Dim hmf As Long, hvm As IntPtr

        Dim str As String = ""   ' * 20

        Dim MyLen As IntPtr = 255

        hmf = OpenFileMapping(4, False, TextBox2.Text)

 

        hvm = MapViewOfFile(hmf, 4, 0, 0, 0)

        If hvm = 0 Then TextBox1.Text = "檔沒有找到!" : Return

        Dim ptr As IntPtr = Marshal.StringToHGlobalAuto(str)

 

        CopyMemory(ptr, hvm, MyLen)

        Dim mystring As String = Marshal.PtrToStringAuto(ptr)

        UnmapViewOfFile(hvm)

        CloseHandle(hmf)

        ptr = 0

        TextBox1.Text = Trim(mystring) & "<結束>"

 

    End Sub

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值