title: Why can't we pass a reference from native C++ to C++/CLI?
body: <p>I use a native C++ code base from C#, with a C++/CLI wrapper built around it (with Visual Studio 2013). There are two projects:</p>
  
  <ul>
  <li>NativeCodeBase: simple C++ project set to be built into a static lib.</li>
  <li>ManagedWrapper: C++/CLI project referencing NativeCodeBase.</li>
  </ul>
  
  <p>I have the following native "interface" in NativeCodeBase:</p>
  
  <pre><code>class ITest {
      virtual void Foo(const std::string&amp; str, MyEnum me) = 0;
  }
  </code></pre>
  
  <p>For which I have a native implementation in the ManagedWrapper project.<br>
  In the header:</p>
  
  <pre><code>class TestManaged : public ITest {
      virtual void Foo(const std::string&amp; str, MyEnum me) override;
  }
  </code></pre>
  
  <p>In the cpp:</p>
  
  <pre><code>void TestManaged::Foo(const std::string&amp; str, MyEnum me) {
      int length = str.length();
  }
  </code></pre>
  
  <p>The MyEnum enum is used both in native and managed code, so in its implementation I use a conditionally compiled C++/CLI extension, to make it usable from C#:</p>
  
  <pre><code>#ifdef _MANAGED
      public
  #endif
      enum class MyEnum : unsigned char
      {
          Baz = 0,
          Qux = 1
      };
  </code></pre>
  
  <p>In my native code I have a reference to <code>ITest</code> and call its <code>Foo</code> function with a local <code>std::string</code> variable. When Foo is called, I can see in the debugger that the string passed as an argument is a valid string object.</p>
  
  <p>The call is similar to this:</p>
  
  <pre><code>void Bar(ITest&amp; test) {
      std::string str = "test";
      test.Foo(str, MyEnum::Baz);
  }
  </code></pre>
  
  <p>However, if I put a breakpoint at the beginning of <code>TestManaged::Foo</code>, the debugger says that str has <code>&lt;undefined value&gt;</code>, and the <code>length()</code> call crashes with undefined reference error in the <code>&lt;xstring&gt;</code> header in the following function:</p>
  
  <pre><code>size_type length() const _NOEXCEPT
  {   // return length of sequence
      return (this-&gt;_Mysize);
  }
  </code></pre>
  
  <p>The debugger displays <code>&lt;undefined value&gt;</code> for the <code>this</code> pointer as well.</p>
  
  <p>What can be the reason for this? References somehow get corrupted when passed between the two libraries?</p>
  
  <p>(Additional info: I used not to build the NativeCodeBase project as a separate lib, but linked all the source files from it into the CLI project, and the same code base worked without any problem. It started failing since I configured it to be built into a separate lib and added a reference in the CLI project to the native one.)</p>