Quote:
Originally Posted by whatsup
Code:
Public Declare PtrSafe Sub Mem_Copy Lib "kernel32" Alias "RtlMoveMemory" ( _
ByRef Destination As Any, _
ByRef Source As Any, _
ByVal Length As Long)
' Platform-independent method to return the full zero-padded
' hexadecimal representation of a pointer value
Function HexPtr(ByVal Ptr As LongPtr) As String
HexPtr = Hex$(Ptr)
HexPtr = String$((PTR_LENGTH * 2) - Len(HexPtr), "0") & HexPtr
End Function
Public Function Mem_ReadHex(ByVal Ptr As LongPtr, ByVal Length As Long) As String
Dim bBuffer() As Byte, strBytes() As String, i As Long, ub As Long, b As Byte
ub = Length - 1
ReDim bBuffer(ub)
ReDim strBytes(ub)
Mem_Copy bBuffer(0), ByVal Ptr, Length
For i = 0 To ub
b = bBuffer(i)
strBytes(i) = IIf(b < 16, "0", "") & Hex$(b)
Next
Mem_ReadHex = Join(strBytes, "")
End Function
Sub ExampleForScalar()
Dim lngValue As Long
lngValue = 100
lng_VarPtr = VarPtr(lngValue)
Debug.Print "lngValue : 0x"; HexPtr(lng_VarPtr); _
" : 0x"; Mem_ReadHex(lng_VarPtr, 4)
End Sub
Sub ValueIsGone()
Debug.Print "lngValue : 0x"; HexPtr(lng_VarPtr); _
" : 0x"; Mem_ReadHex(lng_VarPtr, 4)
End Sub
In this example with ValueIsGone() you track down the pointer obtained from ExampleForScalar() and the reading of Memory says the value is zero.
Now with objects it isn't that easy, and that's where I'm struggling. I trying to recover the object from memory by it's pointer by adding this code:
Code:
Function ObjectFromPointer(lPtr As Long) As Object
Dim oTemp As Object
Mem_Copy oTemp, lPtr, 4
Set ObjectFromPointer = oTemp
End Function
Sub ExampleForObject()
Dim objRange As Object
Set objRange = Sheets(1).Range("A1")
lng_ObjPtr = ObjPtr(objRange)
'Set objRange = Nothing
End Sub
Sub ObjectIsGone()
Dim objRecover As Object
Set objRecover = ObjectFromPointer(lng_ObjPtr)
End Sub
But Mem_Copy in the function ObjectFromPointer() is killing the excel application, no debugging but killing, so be careful with that one.
I'm assuming that the pointer maybe doesn't exist anymore, which would be fine, indicating that the object was taken from memory, but we can have that proof with excel going to hell.
Any idea on this?
|
Yes, the scalar routine (Mem_ReadHex) has a Length parameter that is used to politely reserve bytes for Mem_Copy to blast into. Your object routine has no such parameter. The Mem_Copy routine in ObjectFromPointer is just writing from the base of and Object structure and destroying the VBA Object structure.then you set objRecover to an irregular structure and that's why it crashes.
In order for it to work, you need to figure out the structure of the range object in your example and reserve a buffer with sufficient bytes, for Mem_Copy to dump into.
You need to create a 4 byte buffer just like in the scalar routine to receive the bytes you transfer.