title: Calling a C DLL Function With char* Parameters With P/Invoke
body: <p>I've read other similar questions on this but they don't solve this particular problem. I have an old C-library with a touppercase function (as an example). This takes a char* and returns a char*. However, the pointer returned is a pointer to the same string (don't ask me I didn't write it).</p>
  
  <p>The function looks like this:</p>
  
  <pre><code>__declspec(dllexport)
  char * __cdecl touppercase(char *ps_source)
  {
      char *ps_buffer = NULL;
  
      assert (ps_source != NULL);
  
      ps_buffer = ps_source;
      while (*ps_buffer != '\0')
      {
          *ps_buffer = toupper(*ps_buffer);
          ps_buffer++;
      }
  *ps_buffer = '\0';
      return (ps_source);
  }
  </code></pre>
  
  <p>The C# code to declare this looks like:</p>
  
  <pre><code>    [DllImport("mydll.dll", EntryPoint = "touppercase",
                 CharSet = CharSet.Ansi, ExactSpelling = true,
                 CallingConvention = CallingConvention.Cdecl)]
      private static extern System.IntPtr touppercase(string postData);
  </code></pre>
  
  <p>The call to this in my app looks like</p>
  
  <pre><code>     string sTest2 = Marshal.PtrToStringAnsi(to_uppercase(sTest));
  </code></pre>
  
  <p>However sTest2 just ends up being a random string.</p>
  
  <p>I added a test function to the same dll with the same parameters but this allocates memory locally and copies the string. This works fine. Why does the original version now work?</p>
  
  <p>Note: Updating the dll libraries themselves isn't an option.</p>