Nicholas Humphrey
Nicholas Humphrey

Reputation: 1250

CopyMemory crashes Excel if not put in a function

I have encountered a bizarre problem when experimenting with CopyMemory. I have one piece of code, copied from Bytecomb, that only works if I put it into a function:

I put this at the beginning:

Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSource As Any, ByVal ByteLen As Long)

Working version:

Sub StringTest()
    Dim str1 As String
    Dim pstr1 As LongPtr

    str1 = "PowerVB"
    Debug.Print "Memory  : 0x"; Mem_ReadHex(pstr1 - 4, LenB(str1) + 6)

End Sub

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)
    CopyMemory 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

This program prints out the whole layout of the string in memory perfectly (first 4 bytes indicate the length, followed by the string content, and then 2 bytes of null):

Memory  : 0x0E00000050006F00770065007200560042000000

Now it crashes if I put the function into the sub:

Sub StringTest()
    Dim str1 As String
    Dim str2 As String
    Dim pstr1 As LongPtr

    str1 = "PowerVB"
    CopyMemory pstr1, ByVal VarPtr(str1), 8

    Dim bBuffer() As Byte, strBytes() As String
    ub = LenB(str1) + 5
    ReDim bBuffer(ub)
    ReDim strBytes(ub)
    CopyMemory bBuffer(0), ByVal pstr1 - 4, LenB(str1) + 6 'extra 4 bytes for string length, and 2 bytes of null characters
    For i = 0 To ub
        b = bBuffer(i)
        strBytes(i) = IIf(b < 16, "0", "") & Hex$(b) 'for 2 bytes, if the value < 16, then it only consists of one byte
    Next i
    Debug.Print Join(strBytes, "")
End Sub

I don't get it. What's the difference between the two versions?

Upvotes: 1

Views: 2045

Answers (1)

Nicholas Humphrey
Nicholas Humphrey

Reputation: 1250

OK I found the fix:

CopyMemory bBuffer(0), ByVal pstr1 - 4, ub + 1

Because CopyMemory must take a long as the third parameter, I cannot use LenB(str1) + 6 as it is probably an integer.

Upvotes: 1

Related Questions