|
|
发表于 2005-6-3 01:40:00
|
显示全部楼层
Re:如何读取内存数据
我有一个笨办法,可能速度不理想。在VB6的VBA库中有一个隐藏的模块“_HiddenModule”(需要显示隐藏成员才能在资源浏览器中看见),模块内又有三个隐藏的函数"ObjPtr"、"StrPtr"、"VarPtr",顾名思义是分别获得对象、字符串、变量的地址。三个函数都返回Long型值,就是我们需要的内存地址(相当于C语言中的指针)。利用这些函数返回的地址,再配合Windows API "CopyMemory",将值从获得的地址复制到另一个变量地址,就可以实现像C语言一样的使用指针了。
以下是一个例子,将"SourceVariant"的值通过地址传给"DestinationVariant":
'声明WindowsAPI:
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
'定义源变量(为Byte类型)和存放源变量地址的变量(为Long类型,相当于指针):
Dim SourceVariant as Byte, SourceVariantAddress as Long
'定义目标变量(为Byte类型)和存放目标变量地址的变量(为Long类型,相当于指针):
Dim DestinationVariant as Byte, DestinationVariantAddress as Long
'分别获取源变量和目标变量的内存地址(使用VarPtr函数):
SourceVariantAddress=VBA._HiddenModule.VarPtr(SourceVariant)
DestinationVariantAddress=VBA._HiddenModule.VarPtr(DestinationVariant)
'对源变量任意赋值(本例使SourceVariant的值为100):
SourceVariant=100
'通过地址将源变量的值复制到目标变量(使用CopyMemory函数):
CopyMemory DestinationVariantAddress, SourceVariantAddress, 1 '读取一个字节。
'此时DestinationVariant的值已变为100。
Print DestinationVariant '则打印"100"。
若是读取的变量长度大于字节,则需要改变变量本身的类型和相应的读取长度,如:
CopyMemory IntegerValueAddress1, IntegerValueAddress2, 2 '读取两个字节。
CopyMemory LongValueAddress1, LongValueAddress2, 4 '读取四个字节。
CopyMemory SingleValueAddress1, SingleValueAddress2, 2 '读取两个字节。
CopyMemory DoubleValueAddress1, DoubleValueAddress2, 4'读取四个字节。
若是任意字符串,则最后一个参数为字符串长度加一,因为在C语言中字符串末尾有一个'\0'。
但无论复制何种变量,地址变量类型始终是Long类型,地址变量值的加减变化可改变在内存中的访问位置。
若是使用DirectX做游戏,在DxVBLibA的D3DAUX模块中,有一个函数DxCopyMemory,功能也类似。 |
|