5 <div class=
"mapi-header">
9 <p>GC handles are wrappers that are used to keep references to
10 managed objects in the unmanaged space and preventing the
11 object from being disposed.
13 <p>These are the C equivalents of the
<tt>System.GCHandle
</tt>
16 <p>There are two kinds of GCHandles that can be created:
19 <li>Handles to objects (use
<tt><a
20 href=
"#api:mono_gchandle_new">mono_gchandle_new
</a></tt>).
22 <li>Weak handles to objects (use
<tt><a
23 href=
"#api:mono_gchandle_new_weakref">mono_gchandle_new_weakref
</a></tt>).
24 Weak handles can have the objects reclaimed by the
29 <p>To retrieve the target address of an object pointed to by a
30 <tt>GCHandle
</tt> you should use
31 <tt>mono_gchandle_get_target
</tt>.
33 <p>For example, consider the following C code:
35 <div class=
"mapi-code">
36 static MonoObject* o = NULL;
39 <p>The object in `o' will *NOT* be scanned.
41 <p>If you need to store an object in a C variable and prevent
42 it from being collected, you need to acquire a GC handle for
45 <div class=
"mapi-code">
46 guint32 handle = mono_gchandle_new (my_object, TRUE);
49 <p>TRUE means the object will be pinned, so it won't move in
50 memory when we'll use a moving GC. You can access the
51 MonoObject* referenced by a handle with:
53 <div class=
"mapi-code">
54 MonoObject* obj = mono_gchandle_get_target (handle);
57 <p>When you don't need the handle anymore you need to call:
59 <div class=
"mapi-code">
60 mono_gchandle_free (handle);
63 <p>Note that if you assign a new object to the C var, you need
64 to get a new handle, it's not enough to store a new object in
67 <p>So code that looked like this:
69 <div class=
"mapi-code">
70 static MonoObject* obj = NULL;
72 obj = mono_object_new (...);
75 // when done to allow the GC to collect obj
79 <p>should now be changed to:
81 <div class=
"mapi-code">
82 static guint32 o_handle;
84 MonoObject *obj = mono_object_new (...);
85 o_handle = mono_gchandle_new (obj, TRUE);
86 // use o or mono_gchandle_get_target (o_handle)
88 // when done to allow the GC to collect obj
89 mono_gchandle_free (o_handle);
92 <h4><a name=
"api:mono_gchandle_new">mono_gchandle_new
</a></h4>
93 <h4><a name=
"api:mono_gchandle_new_weakref">mono_gchandle_new_weakref
</a></h4>
94 <h4><a name=
"api:mono_gchandle_get_target">mono_gchandle_get_target
</a></h4>
95 <h4><a name=
"api:mono_gchandle_free">mono_gchandle_free
</a></h4>