// Convert an object to a GCHandle object myObject = new object(); GCHandle handle = GCHandle.Alloc(myObject, GCHandleType.Weak); // Use the handle to access the object if (handle.Target != null) { // Do something with the object } // Free the handle when done handle.Free();
// Convert a string to a GCHandle string myString = "Hello, world!"; IntPtr handle = GCHandle.ToIntPtr(GCHandle.Alloc(myString, GCHandleType.Pinned)); // Use the handle to access the underlying memory byte[] bytes = new byte[myString.Length * sizeof(char)]; Marshal.Copy(handle, bytes, 0, bytes.Length); // Free the handle when done GCHandle.FromIntPtr(handle).Free();This example demonstrates how to create a pinned handle to a string and use it to access the underlying memory. The handle is allocated with the GCHandleType.Pinned option, which means that the object will not be moved by the garbage collector. The handle is converted to an IntPtr so that it can be used with the Marshal.Copy method. These examples use the System.Runtime.InteropServices namespace, which is included in the .NET Framework.