How to move an "unmanaged" pointer?

I have an external method that takes some parameters, allocates memory and returns a pointer.

[DllImport("some.dll", CallingConvention = CvInvoke.CvCallingConvention)] public static extern IntPtr cvCreateHeader( Size size, int a, int b); 

I am well aware that the wrong practice is to allocate unmanaged memory in a managed application, but in this case I have no choice, since the dll is third-party.

There is an equivalent function that frees memory, and I know what size the allocated array is.

  • How to bind the returned pointer so that the GC does not move it (without going unsafe)? "fixed" will not do this because this pointer is widely used throughout the class?
  • Is there a better methodology for this p / Invoke?
+6
source share
1 answer

No, you are returning a pointer to a memory that will never move. The memory allocated from the built-in heap remains placed, nothing like the compaction strategy that the garbage collector uses. This can only work if the memory management system can find all the pointers that point to the allocated memory fragment. So that he can update these pointers when the piece moves. Nothing of the sort exists for native code; there is no reliable way to find these pointers.

Don't bother looking for a way to bind a pointer. There is not one, because there is no need for one.

+11
source

All Articles