Creating unmanaged memory using Marshal.AllocHGlobal is simple.
IntPtr pointer = Marshal.AllocHGlobal(1024);
If you need to calculate the amount of space you can use Marshal.SizeOf.
int size = Marshal.SizeOf(typeof(IntPtr));
IntPtr pointer = Marshal.AllocHGlobal(size);
You will also need to enable unsafe code
in your project for this to run.
- Right click on your project and select
Properties
. - Open the
Build
tab. - Select
Allow unsafe code
.