title: Allocate memory in a C++ dll, free in C#
body: <p>I am new in C# and trying to communicate C# with C++ dll. My main purpose is allocating memory in C# using <code>Marshal.AllocHGlobal()</code>, assign values in it and pass the reference of <code>IntPtr</code> to C++ dll. On the side of C++ dll, I'm changing the allocated memory size with <code>malloc()</code>, assign variables. In the end, I print values in C#. Until this point, everything works fine.</p>
  
  <p>But when I try to free allocated memory in C# with <code>Marshal.FreeHGlobal()</code>, I get an error.</p>
  
  <p>Actually, I search a lot to how I should implement my code with these functions. I found a solution that says I must write a function in the DLL for deallocating the memory and call this function. But my manager told me, I need to do this work in C# side. So I can't use that solution. Also, I found some other ideas which use COM but the manager doesn't want to use COM. So I can't use COM. Here some codes;</p>
  
  <p>Allocating the memory in C#</p>
  
  <pre class="lang-cs prettyprint-override"><code>var offset = 0;
  var size = Marshal.SizeOf(typeof(dVehicle)) * denemeVehicle.Count();
  IntPtr vehPnt;
  vehPnt = Marshal.AllocHGlobal(size);
  
  for(var i = 0; i &lt; denemeVehicle.Count(); i++)
  {
      Marshal.StructureToPtr(denemeVehicle[i], new IntPtr(vehPnt.ToInt64() + offset), false);
      offset += Marshal.SizeOf(typeof(dVehicle));
  }
  </code></pre>
  
  <p>Changing the allocated memory size in C++</p>
  
  <pre class="lang-cpp prettyprint-override"><code>*vehicles = (dVehicle*) malloc(sizeof(dVehicle) * (new_VehSize));
  </code></pre>
  
  <p>Free the allocated memory</p>
  
  <pre class="lang-cs prettyprint-override"><code>Marshal.FreeHGlobal(vehPnt); // The error shows up in here
  </code></pre>
  
  <p>And this is error message;</p>
  
  <blockquote>
    <p>The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))</p>
  </blockquote>