byte[] buffer = new byte[1024]; IntPtr ptr = Marshal.AllocHGlobal(buffer.Length); Marshal.Copy(buffer, 0, ptr, buffer.Length);
[StructLayout(LayoutKind.Sequential)] struct MyStruct { public int x; public int y; } MyStruct data = new MyStruct { x = 10, y = 20 }; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(data)); Marshal.StructureToPtr(data, ptr, false);In this example, a simple structure is defined with two integer fields. The AllocHGlobal method is used to allocate unmanaged memory for the structure, and the Marshal.StructureToPtr method is used to copy the contents of the managed structure to the unmanaged memory. Package library: This is a built-in method in the .NET Framework and does not require any external package/library.