Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pin an 'unmanaged' pointer?

Tags:

c#

pinvoke

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?
like image 227
Gilad Avatar asked Jan 22 '13 12:01

Gilad


1 Answers

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.

like image 178
Hans Passant Avatar answered Oct 20 '22 16:10

Hans Passant