Gilad
Gilad

Reputation: 2886

How to pin an 'unmanaged' pointer?

I have an external method that receives 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'm well aware that it is bad practice to allocate unmanaged memory in a managed application but in this case I have no choice as the dll is 3rd party.

There is an equivalent function that releases the memory and I do know what is the size of the allocated array.

  1. How do I pin the returned pointer so the GC does not move it (without going unsafe)? 'fixed' won't do it as this pointer is widely used throughout the class?
  2. Is there a better methodology for this p/Invoke?

Upvotes: 6

Views: 1060

Answers (1)

Hans Passant
Hans Passant

Reputation: 941585

No, you are getting back a pointer to memory that will never move. Memory allocated from a native heap stays put, there's nothing similar to the compacting strategy that a garbage collector uses. That can only work when a memory management system can find all the pointers that point to an allocated chunk of memory. So that it can update those pointers when the chunk moves. Nothing like that exists for native code, there is no reliable way to find those pointers back.

Do not bother looking for a way to pin the pointer. There isn't one because there is no need for one.

Upvotes: 11

Related Questions