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

前端 未结 1 1229
南旧
南旧 2021-01-27 07:19

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

My first attempt was the following:

int bytes = 10;
IntPtr ip = Marshal.AllocHGlobal(bytes);
G         


        
相关标签:
1条回答
  • 2021-01-27 08:01

    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.

    0 讨论(0)
提交回复
热议问题