Almesi
Almesi

Reputation: 84

MoveMemory returns different Value

I'm trying to implement pointers in VBA.

Private Declare PtrSafe Sub MoveMemory Lib "kernel32.dll" Alias "RtlMoveMemory" _
    (ByVal Destination As LongPtr, ByVal Source As LongPtr, ByVal Length As Long)

Public Function AL_Address(Variable As Variant) As LongPtr
    AL_Address = VarPtr(Variable)
End Function

Public Function AL_DeRef(Pointer As LongPtr, Variable As Variant) As Variant
    Select Case VarType(Variable)
        Case vbInteger:         AL_DeRef = AL_DeRef_Integer(Pointer)
        Case vbLong:            AL_DeRef = AL_DeRef_Long(Pointer)
        Case vbSingle:          AL_DeRef = AL_DeRef_Single(Pointer)
        Case vbDouble:          AL_DeRef = AL_DeRef_Double(Pointer)
        Case vbCurrency:        AL_DeRef = AL_DeRef_Currency(Pointer)
        Case vbDate:            AL_DeRef = AL_DeRef_Date(Pointer)
        Case vbString:          AL_DeRef = AL_DeRef_String(Pointer)
        Case vbObject:          AL_DeRef = AL_DeRef_Object(Pointer)
        Case vbBoolean:         AL_DeRef = AL_DeRef_Boolean(Pointer)
        Case vbByte:            AL_DeRef = AL_DeRef_Byte(Pointer)
        Case vbLongLong:        AL_DeRef = AL_DeRef_LongLong(Pointer)
    End Select
End Function

Private Function AL_DeRef_Integer(Pointer As LongPtr) As Integer
    Dim Temp As Integer
    MoveMemory VarPtr(AL_DeRef_Integer ), Pointer, Len(Temp)
End Function

Sub Test()
    Dim a As Integer, b As Integer, c As Integer
    a = 1: b = 2: c = 0
    c = AL_DeRef(AL_Address(a), a)
    Debug.Print a
    Debug.Print b
    Debug.Print c
End Sub

This Code works like this:

AL_Address gets the Address of any Variant-Datatype
AL_DeRef takes any Variant and decides which Dereferancation to call
For simplicity I just used the one for Integer
AL_DeRef_Integer moves (in theory) the memory of the Pointer to the return Value

Test should be:

1
2
1

But I get:

1
2
16387

I tried https://www.mrexcel.com/board/threads/pointer-in-vba.484356/ by Akihito Yamashiro and that worked fine but trying it to implement for myself doesn't work like intended.
The Bytesize of Len(Temp) works without problems.
I tried this and it didn't work:

Private Function AL_DeRef_Integer(Pointer As LongPtr) As Integer
    Dim Temp As Integer
    MoveMemory VarPtr(Temp), Pointer, Len(Temp)
    AL_DeRef_Integer = Temp
End Function

Upvotes: 0

Views: 46

Answers (0)

Related Questions