[LoongArch64] Part-5:add loongarch support in some files for LoongArch64. (#21769)
[mono-project.git] / docs / sources / mono-api-gchandle.html
blob3ff8536dd396ddad5a129b88c9509657126f2456
1 <h1>GC Handles</h1>
3 <h3>Synopsys</h3>
5 <div class="mapi-header">
6 @API_IDX@
7 </div>
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>
14 structure.
16 <p>There are two kinds of GCHandles that can be created:
18 <ul>
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
25 garbage collector.
27 </ul>
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;
37 </div>
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
43 it.
45 <div class="mapi-code">
46 guint32 handle = mono_gchandle_new (my_object, TRUE);
47 </div>
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);
55 </div>
57 <p>When you don't need the handle anymore you need to call:
59 <div class="mapi-code">
60 mono_gchandle_free (handle);
61 </div>
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
65 the C var.
67 <p>So code that looked like this:
69 <div class="mapi-code">
70 static MonoObject* obj = NULL;
71 ...
72 obj = mono_object_new (...);
73 // use obj
74 ...
75 // when done to allow the GC to collect obj
76 obj = NULL;
77 </div>
79 <p>should now be changed to:
81 <div class="mapi-code">
82 static guint32 o_handle;
83 ...
84 MonoObject *obj = mono_object_new (...);
85 o_handle = mono_gchandle_new (obj, TRUE);
86 // use o or mono_gchandle_get_target (o_handle)
87 ...
88 // when done to allow the GC to collect obj
89 mono_gchandle_free (o_handle);
90 </div>
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>