title: Passing String from Native C++ DLL to C# App
body: <p>I have written a DLL in C++. One of the functions writes to a character array.</p>
  
  <p>C++ Function</p>
  
  <pre><code>EXPORT int xmain(int argc, char argv[], char argv2[])
  {
      char  pTypeName[4096];
      ...
      //Other pTypeName ends up populated with "Portable Network Graphics"
      //This code verifies that pTypeName is populated with what I think it is:
      char szBuff[64];
      sprintf(szBuff, pTypeName, 0);
      MessageBoxA(NULL, szBuff, szBuff, MB_OK);
      //The caption and title are "Portable Network Graphics"
  
      ...
      //Here, I attempt to copy the value in pTypeName to parameter 3.
      sprintf(argv2, szBuff, 0);
  
      return ret;
  }
  </code></pre>
  
  <p>C# Import</p>
  
  <pre><code>    //I believe I have to use CharSet.Ansi because by the C++ code uses char[],
      [DllImport("FirstDll.dll", CharSet=CharSet.Ansi)]
      public static extern int xmain(int argc, string argv, ref string zzz);
  </code></pre>
  
  <p>C# Function</p>
  
  <pre><code>private void button2_Click(object sender, EventArgs e)
  {
      string zzz = ""; 
      int xxx = xmain(2, @"C:\hhh.bmp", ref zzz);
      MessageBox.Show(zzz);
  
      //The message box displays
      //MessageBox.Show displays "IstuÈst¼ÓstÄstlÄstwÄstiÑstõÖstwÍst\
      // aÖst[ÖstÃÏst¯ÄstÐstòÄstŽÐstÅstpÅstOleMainThreadWndClass"
  
  }
  </code></pre>
  
  <p>I have attempted to pass a parameter from C# by reference and have the C++ DLL populate the parameter. Even though I have verified that the value is correct in the DLL, gibberish gets passed to the C# application. </p>
  
  <p>What can I do to write the correct string value to the C# string?</p>