关于RtlMoveMemory(CopyMemory)的VBA代码调试求助
Fixing Your RtlMoveMemory (CopyMemory) VBA Code
Let's break down why your code isn't updating the value of c as expected, and fix it step by step.
The Core Issue
Your CopyMemory calls are misusing pointer addresses—you're copying the address values themselves instead of the data those pointers point to. Here's where you went wrong:
- In the first
CopyMemorycall, you're writing the address ofc(stored inpointerOfi) into the memory location oftempvalue, not reading the actual value ofc. - In the second call, you're writing the address of
tempvalueback intopointerOfi, not writing the updatedtempvalueback toc's memory space.
Corrected Code
First, let's adjust the CopyMemory declaration to better match how RtlMoveMemory works (it expects raw pointer addresses, so using ByVal for pointer parameters is more accurate):
Option Explicit #If VBA7 Then Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" ( _ ByVal Destination As LongPtr, _ ByVal Source As LongPtr, _ ByVal Length As LongPtr _ ) #Else Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" ( _ ByVal Destination As Long, _ ByVal Source As Long, _ ByVal Length As Long _ ) #End If Sub Main2() Dim c As Long, d As Long c = 3 Move2 VarPtr(c) Debug.Print c ' Now outputs 4 as expected! End Sub Sub Move2(ByVal pointerOfi As LongPtr) Dim tempvalue As Long ' 1. Read the value from c's memory address (stored in pointerOfi) into tempvalue CopyMemory tempvalue, ByVal pointerOfi, LenB(tempvalue) ' 2. Increment the temporary value tempvalue = tempvalue + 1 ' 3. Write the updated value back to c's memory address CopyMemory ByVal pointerOfi, tempvalue, LenB(tempvalue) End Sub
What Changed?
- Reading the value:
CopyMemory tempvalue, ByVal pointerOfi, LenB(tempvalue)tellsCopyMemoryto take the address stored inpointerOfi(the location ofc), read 4 bytes (the size of aLong), and store that data intempvalue. - Writing the value:
CopyMemory ByVal pointerOfi, tempvalue, LenB(tempvalue)reverses the process—it takes the updated data intempvalueand writes it back to the original memory address ofc, modifying the variable directly.
Alternative (Using VarPtr Explicitly)
If you prefer to use VarPtr to specify addresses directly (instead of relying on VBA to pass variable addresses implicitly), this version works identically:
Sub Move2(ByVal pointerOfi As LongPtr) Dim tempvalue As Long CopyMemory VarPtr(tempvalue), pointerOfi, LenB(tempvalue) tempvalue = tempvalue + 1 CopyMemory pointerOfi, VarPtr(tempvalue), LenB(tempvalue) End Sub
内容的提问来源于stack exchange,提问作者Solus161
相关产品推荐
相关产品推荐

