问题
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
.
回答1:
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.
来源:https://stackoverflow.com/questions/40539292/how-to-pin-memory-allocated-by-marshal-allochglobal-in-c