cycloidistic cycloidistic - 29 days ago 15
C# Question

How to pin memory allocated by Marshal.AllocHGlobal() in C#?

How do you pin memory allocated by Marshal.AllocHGlobal()?

My first attempt was the following:

int bytes = 10;
IntPtr ip = Marshal.AllocHGlobal(bytes);
GCHandle iph = GCHandle.Alloc(ip, GCHandleType.Pinned);


Although I think this only pins the
IntPtr
and not the block of memory referred to by the
IntPtr
.

Answer

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.