// Allocate an unmanaged object and get its handle IntPtr hObject = SomeUnmanagedApi.AllocateObject(); // Convert the handle to a managed object reference object managedObject = GCHandledObjects.GCHandleToObject(hObject); // Use the managed object reference DoSomethingWithObject(managedObject); // Release the unmanaged object SomeUnmanagedApi.FreeObject(hObject);
// Define a structure for passing data to an unmanaged function [StructLayout(LayoutKind.Sequential)] struct SomeData { public int Value1; public int Value2; } // Create a managed object and pin it in memory SomeData data = new SomeData { Value1 = 42, Value2 = 84 }; GCHandle gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr pData = gcHandle.AddrOfPinnedObject(); // Call an unmanaged function and pass the object SomeUnmanagedApi.DoSomethingWithData(pData); // Release the pinned object gcHandle.Free();In this example, we create a managed object of a custom structure type, pin it in memory using GCHandle, and obtain a pointer to its memory location using AddrOfPinnedObject. We can then pass this pointer to an unmanaged function that expects a pointer to the structure. After the function returns, we release the pinned object using GCHandle.Free. The GCHandledObjects and GCHandleToObject classes and methods are part of the core .NET framework, and do not require any additional package or library.