473,657 Members | 2,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

weird GCHandle behavior

XYZ
I need to pass the address of a variableto some win32 API functions like
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?
Nov 21 '05 #1
8 2342
"XYZ" <x@y.z> schrieb:
I need to pass the address of a variableto some win32 API functions like
RTLMoveMemor y

I noticed some weird behavior when pinning objects and using the handle's
pointer to write data to the memory location.


I would never change a string's data using unmanaged code because it can
lead to misbehaving code. Strings in .NET are immutable and thus should not
be manipulated, because otherwise it is not guaranteed that all the string
object's methods and properties still work as specified.

You can either pass a 'String' variable 'ByVal' when using VB.NET's
'Declare' statement, or you can use a 'StringBuilder' object.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #2
>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.
No, since GCHandle.Alloc takes an Object parameter, you end up pinning
a boxed copy of c. You can't pin c since it's stack allocated.

Assigning 100 to Target just creates a new boxed Integer, it doesn't
affect the original object.

s = "allo"

gh2.Target = "hello"
>>>>>>

again, no change in "s"

Of course not, you're just reassigning the Target reference to another
object. If we forget about GCHandle for a while and just look at
regular variables, you have the same situation

s = "allo"
Dim target As String = s
target = hello"

' now target is "hello" but s remains unchanged as "allo"

what is going on? I thought that if I "pin" an object using a handle,
gchandle.addre ssofpinnedobjec t will be a pointer to my variable and changing
the memory value at the pointer will change my variable as well


Right, but you're not "changing the memory value at the pointer" by
reassigning Target. And if you change a boxed copy of a value type,
you have to unbox it to see the changes.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 21 '05 #3
XYZ
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
"XYZ" <x@y.z> schrieb:
I need to pass the address of a variableto some win32 API functions like
RTLMoveMemo ry

I noticed some weird behavior when pinning objects and using the handle's
pointer to write data to the memory location.


I would never change a string's data using unmanaged code because it can
lead to misbehaving code. Strings in .NET are immutable and thus should
not be manipulated, because otherwise it is not guaranteed that all the
string object's methods and properties still work as specified.


what does "immutable" mean?

finally I'm saving the string as a byte array and reconstructing the class
from it, so this is not an issue
Nov 21 '05 #4
XYZ
"Mattias Sjögren" <ma************ ********@mvps.o rg> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
No, since GCHandle.Alloc takes an Object parameter, you end up pinning
a boxed copy of c. You can't pin c since it's stack allocated.


aaargh! I forgot about that, obviously if it's on the stack it can't be in
the general memory

so, what happens then? does this call to alloc actually allocate space in
memory?
what is a "boxed copy" ?
Nov 21 '05 #5
"XYZ" <x@y.z> schrieb:
I need to pass the address of a variableto some win32 API functions like
RTLMoveMemor y

I noticed some weird behavior when pinning objects and using the
handle's pointer to write data to the memory location.


I would never change a string's data using unmanaged code because it can
lead to misbehaving code. Strings in .NET are immutable and thus should
not be manipulated, because otherwise it is not guaranteed that all the
string object's methods and properties still work as specified.


what does "immutable" mean?


It means that the object's data cannot/must not be changed.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #6
XYZ
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:uM******** ******@tk2msftn gp13.phx.gbl...
"XYZ" <x@y.z> schrieb:
I need to pass the address of a variableto some win32 API functions like
RTLMoveMemo ry

I noticed some weird behavior when pinning objects and using the
handle's pointer to write data to the memory location.

I would never change a string's data using unmanaged code because it can
lead to misbehaving code. Strings in .NET are immutable and thus should
not be manipulated, because otherwise it is not guaranteed that all the
string object's methods and properties still work as specified.


what does "immutable" mean?


It means that the object's data cannot/must not be changed.


is there a list of classes/objects that are immutable, and those that
aren't?
Nov 21 '05 #7
so, what happens then? does this call to alloc actually allocate space in
memory?
The boxing of the integer will allocate an object on the heap, and a
reference to that is passed to Alloc.

what is a "boxed copy" ?


Boxing is basically a way to embed a value type value in a heap
allocated object. You can read more about boxing in the documentation.

The "box" object contains a copy of the value, so there's no
connection back to the original value. Changing the boxed object will
not affect the original.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 21 '05 #8
"XYZ" <x@y.z> schrieb:
>I need to pass the address of a variableto some win32 API functions
>like RTLMoveMemory
>
> I noticed some weird behavior when pinning objects and using the
> handle's pointer to write data to the memory location.

I would never change a string's data using unmanaged code because it
can lead to misbehaving code. Strings in .NET are immutable and thus
should not be manipulated, because otherwise it is not guaranteed that
all the string object's methods and properties still work as specified.

what does "immutable" mean?


It means that the object's data cannot/must not be changed.


is there a list of classes/objects that are immutable, and those that
aren't?


Most classes are not immutable. The documentation of the string class
clearly states that this class' instances are immutable. I doubt that there
is an overview over immutable classes.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1673
by: Dietmar Hauser | last post by:
Hello, I'm using AppDomains to launch another .NET application from within my application. The code looks like this: <snip> try { AppDomain app = AppDomain.CreateDomain( guestAppName );
1
5885
by: Jonathan Yong | last post by:
I observe a very weird behavior when dynamically create web control and bind events to it. Create a C# ASP.NET application, Put a PlaceHolder and Textbox onto the Web form, and try with the 4 code scenerio below. --------------------------------------------------------------------------- Scenerio 1
1
2603
by: Hexar Anderson | last post by:
Why can't you pin an enumeration? For example, the with the following code: public enum MyEnum : byte { ValueOne = 1, ValueTwo = 2 } public class MyClass {
4
2656
by: darrel | last post by:
I'm trying to get a page up using some sample code that interfaces with a 3rd party application using .net. The sample code the company provides, when I run it, produces this error: ================================================================== An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll Additional information: Cannot pass a GCHandle across app domains....
0
1103
by: Lonewolf | last post by:
Hi, please pardon me if I sound stupid. I want to check the status of the GChandle to see if a previous call to Alloc is successful, or whether it has been called before hand, before I call the Free function. I tried the following code, GCHandle gch; gch=GCHandle::Alloc(Mydelegate); <== How do I check if this is successful? gch.Free();
2
7900
by: steve | last post by:
Hi all, I want to understand more about how the pinvoke pinning process works. I'm writing some code that calls DeviceIoControl. DeviceIoControl provides a generic interface to device drivers. Its signature is deliberately open-ended so that it can be highly generic. Refer SDK for more. I want to access the drive geommetry of an SD-Card via
1
4613
by: =?Utf-8?B?SkE=?= | last post by:
I use a method for threading that instantiates an object that is a wrapper to a DLL (written in C). The wrapper class is passed a byte array, and then does GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr ptr = (IntPtr)(handle.AddrOfPinnedObject().ToInt32() + buffer.Length-1); It passes ptr to the DLL function FunctionX().
7
6433
by: DaTurk | last post by:
Hi, I'm coding up an application that has a native c++ layer, asynchronously calling callback in a CLI layer. We originally did this with static inline methods in the CLI layer, but this solution only works with singleton objects. So I have to explore other solutions. So beside pinning pointers, I've been looking at GCHandle. I was
0
1424
by: DaTurk | last post by:
Hi, I need to have a native class hold on to a managed function pointer. Not a unmanaged class in a manged block. I mean an unmanaged class in an unmanaged block via #pragma unmanaged. I'm wondering if GCHandle will be enough. I can't use gcroot because it's a #pragma unmananged so if I declare a gcrooted variable gcroot<ManagedDelegateInstance^pointer
0
8407
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8837
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8739
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8512
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8612
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4171
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2739
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.