title: How to free memory in C# that is allocated in C++
body: <p>I have a C++ dll which is reading video frames from a camera.  These frames get allocated in the DLL returned via pointer to the caller (a C# program).</p>
  
  <p>When C# is done with a particular frame of video, it needs to clean it up.   The DLL interface and memory management is wrapped in a disposable class in C# so its easier to control things.   However, it seems like the memory doesn't get freed/released.   The memory footprint of my process grows and grows and in less than a minute, I get allocation errors in the C++ DLL as there isn't any memory left.   </p>
  
  <p>The video frames are a bit over 9 MB each.   There is a lot of code, so I'll simply provide the allocation/deallocations/types/etc.</p>
  
  <p>First : Allocation in C++ of raw buffer for the camera bytes.</p>
  
  <pre><code>dst = new unsigned char[mFrameLengthInBytes];
  </code></pre>
  
  <p>Second : transfer from the raw pointer back to across the DLL boundary as an unsigned char * and into an IntPtr in C#</p>
  
  <pre><code>IntPtr pFrame = VideoSource_GetFrame(mCamera, ImageFormat.BAYER);
  return new VideoFrame(pFrame, .... );
  </code></pre>
  
  <p>So now the IntPtr is passed into the CTOR of the VideoFrame class.  Inside the CTOR the IntPtr is copied to an internal member of the class as follows :</p>
  
  <pre><code>IntPtr dataPtr;
  public VideoFrame(IntPtr pDataToCopy, ...)
  {
      ...
      this.dataPtr = pDataToCopy;
  }
  </code></pre>
  
  <p>My understanding is that is a shallow copy and the class now references the original data buffer.    The frame is used/processed/etc.   Later, the VideoFrame class is disposed and the following is used to clean up the memory.</p>
  
  <pre><code>Marshal.FreeHGlobal(this.dataPtr);
  </code></pre>
  
  <p>I suspect the problem is that... dataPtr is an IntPtr and C# has no way to know that the underlying buffer is actually 9 MB, right?    Is there a way to tell it how much memory to release at that point?   Am I using the wrong C# free method?   Is there one specifically for this sort of situation?</p>