How do you pin memory allocated by Marshal.AllocHGlobal()?
My first attempt was the following:
int bytes = 10;
IntPtr ip = Marshal.AllocHGlobal(bytes);
G
The memory allocated by AllocHGlobal
is already pinned. the IntPtr
that is returned is the address of the pinned location.
UPDATE: To be pedantic you can't actually "pin" the memory allocated by AllocHGlobal
, to pin something means to tell the Garbage Collector to not move the object in memory. The memory allocated by AllocHGlobal
is "unmanaged memory" which means it is memory that is not managed by the Garbage Collector.
No process besides the Garbage Collector moves memory around in your program, and the Garbage Collector does not care about unmanaged resources.