title: PInvokeStackImbalance when calling a DLL function from C++/CLI
body: <p>While working on a C++/CLI project to wrap a native C++ DLL, I've come across a native function that takes in a <code>std::string</code>. Something like the following:</p>
  
  <pre><code>class NativeApi
  {
  public:
    ErrorCode readFile(std::string filename = "path.csv");
  };
  </code></pre>
  
  <p>Inside my managed wrapper implementation I allocate a new instance of the native class and call this function:</p>
  
  <pre><code>ref class ManagedApi
  {
  private:
    NativeApi *api;
  public:
    ManagedApi(): api(new NativeApi()) { }
    void Read()
    {
      api-&gt;readFile("apath.csv") // or with nothing to use default value
    }
  }
  </code></pre>
  
  <p>When I run this, I get the MDA <code>PinvokeStackImbalance</code> complaining that this call has unbalanced the stack. I was surprised, since the only other time I ever got this MDA was from C# when calling conventions didn't match. I never saw this happen with C++/CLI, where presumably all the matching is done automatically by the compiler.</p>
  
  <p>Has anyone ever saw this before? Googling came up empty. I've looked at the DLL signature and it looks something like:</p>
  
  <p><code>?readFile@NativeApi@@QAE?AW4ErrorCode@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z</code></p>
  
  <p>This tells me that the function is there, and takes as a sole argument a <code>basic_string</code>, which should match the standard <code>std::string</code> typedef.</p>
  
  <p>No idea what could possibly have gone wrong. I can make other calls to the native API that do not involve strings perfectly fine.</p>