byte[] buffer = new byte[1024]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr ptr = handle.AddrOfPinnedObject(); // use ptr to pass buffer to unmanaged code handle.Free();
[DllImport("example.dll")] static extern void DoSomething([In] ref MyClass obj); void Test() { MyClass obj = new MyClass(); GCHandle handle = GCHandle.Alloc(obj); DoSomething(ref obj); handle.Free(); }In this example, a managed object of type MyClass is allocated and pinned using GCHandle. The object is then passed by reference to an unmanaged function using P/Invoke. Finally, the handle is freed to allow garbage collection to clean up the memory. The GCHandle class is part of the System.Runtime.InteropServices namespace, which is included in the .NET Framework Class Library.