RTLMoveMemory
I noticed some weird behavior when pinning objects and using the handle's
pointer to write data to the memory location.
it seems as if after pinning an object the memory and the object are not
updated at the same time anymore
let's say I have this code:
Dim c As Integer
Dim s As String = ""
Dim s2 As String = ""
Dim b(5) As Byte
Dim gh1 As System.Runtime. InteropServices .GCHandle =
System.Runtime. InteropServices .GCHandle.Alloc (c,
Runtime.Interop Services.GCHand leType.Pinned)
Dim gh2 As System.Runtime. InteropServices .GCHandle =
System.Runtime. InteropServices .GCHandle.Alloc (s,
Runtime.Interop Services.GCHand leType.Pinned)
Dim gh3 As System.Runtime. InteropServices .GCHandle =
System.Runtime. InteropServices .GCHandle.Alloc (b,
Runtime.Interop Services.GCHand leType.Pinned)
c = 5
gh1.Target = 100
>>>>>>>>> >>
I made gh1 a handle to "c" and pinned "c". now the value of c and the value
of the target of gh1 in memory change independently. If I copy something to
the location pointed by gh1.addressofpi nnedobject, "c" will not change.
s = "allo"
gh2.Target = "hello"
>>>>
again, no change in "s"
s2 = "will it work?"
Dim gh4 As System.Runtime. InteropServices .GCHandle =
System.Runtime. InteropServices .GCHandle.Alloc (s2,
Runtime.Interop Services.GCHand leType.Pinned)
>>>>>> >>
the order of operations also matters. If I pin S2 before assigning the
string to it, gh4.target is an empty string
if I pin it after assigning a string, gh4.target will say "will it work?"
but any further changes to S2 will not change the string in memory
CopyMemory(gh2. AddrOfPinnedObj ect().ToInt32, gh4.AddrOfPinne dObject.ToInt32 ,
s2.Length)
>>>>>> >
after this call, gh2.target will show "will ", I assume because the original
string was only 5 characters long
but S is still unchanged
HOWEVER, the following code:
b(0) = 100
will immediately affect gh3.target and if I copy something to
gh3.addressofpi nnedobject then array "b" will change right away
what is going on? I thought that if I "pin" an object using a handle,
gchandle.addres sofpinnedobject will be a pointer to my variable and changing
the memory value at the pointer will change my variable as well
this only works if the pinned object is an array, otherwise I can change the
value in memory (using the pointer from the handle) but my local var doesn't
change value. why?