Wednesday, December 17, 2008

[vb6] CopyMemory and array copying

The CopyMemory API function is extremely handy in many situations, especially when calling API functions or subclassing. The reason is that, unlike some other languages, in VB you cannot access a variable via its memory address. A workaround is to do a physical copy of the data between variables. The declare for the function is very flexible - you can pass any data type for its source and destination parameters, and you can pass them ByVal or Byref - just state "ByVal" in the function call if calling ByVal. The last parameter is for indicating the number of bytes to copy.
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(pDst As Any, pSrc As Any, ByVal ByteLen As Long)
As an example of using CopyMemory, the code snippet below copies 11 elements from one array to another array, without having to reference each and every array slot. Note that in this case, the parameters can be passed ByRef (as for the pDst parameter) or ByVal as for the pSrc parameter. In the last case a pointer to the first element of the source array is obtained with the (hidden) VarPtr function.
    Dim i As Integer
Dim Receiver(10) As Long
Dim Source(5 To 15) As Long
For i = 5 To 15
Source(i) = i
Next

CopyMemory Receiver(0), ByVal VarPtr(Source(5)), LenB(Source(5)) * 11

No comments:

Post a Comment

Post a Comment