CopyMemory confusion !!!!
Hi,
the code below uses the CopyMemory API to copy the address of the variable X to a variable Y.
after carrying out the copying of memory, the variable Y should contain the value in X.
Then , if I change the value in X, the variable Y SHOULD now contain the new X value BUT that's not the case as the following test code shows :
VB Code:
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(pDst As Long, pSrc As Long, ByVal ByteLen As Long)
Sub test()
Dim x As Long
Dim y As Long
x = 123
CopyMemory y, x, LenB(x)
MsgBox y ' this show 123 as expected
x = 888
MsgBox y ' this should show 888 but shows 123 instead !!!!
End Sub
Why is Y - in the second MsgBox - still showing (123) instead of showing the new value in X ie(888)?!
Am I missing something ? :confused:
Any help much appreciated .
Re: CopyMemory confusion !!!!
Quote:
Originally Posted by BLUE_SEA
Then , if I change the value in X, the variable Y SHOULD now contain the new X value
No it shouldn't - you are copying the value.
Your code is essentially the same as this:
VB Code:
Dim x As Long
Dim y As Long
x = 123
y = x '(y = 123)
MsgBox y ' this show 123 as expected
x = 888
MsgBox y 'you have only changed X, so y is still 123
Re: CopyMemory confusion !!!!
Thanks Si_The_Geek,
So what's the use of CopyMemory ?
How would I use CopyMemory in this context to have two different pointers pointing to the same variable ??
Regards.
Re: CopyMemory confusion !!!!
You can't change the pointer of a variable
You can get the pointer of a variable using the VarPtr function
what are you trying to do?
Re: CopyMemory confusion !!!!
Quote:
Originally Posted by moeur
You can't change the pointer of a variable
You can get the pointer of a variable using the VarPtr function
what are you trying to do?
I am trying to understand the workings of the CopyMemory API. I thought one of its uses was to be able to copy a memory address from one Pointer to another so we can have two different Pointers poiting to the same variable kind of like using the Set VB statement to point to an object .
Regards.
Re: CopyMemory confusion !!!!
As Si pointed out copy memory copies what is pointed to to a new location not the pointer.
Uses in VB are limited. It is usually used when working with API function that return a UDT. Do a search for copymemory in these forums and you'll see examples of when it is used.