title: How to send a string by reference to an unmanaged C library that modifies that string?
body: <p>I am new to the world of interacting with unmanaged libraries. I have an unmanaged C function that modifies a string by reference within the function. I'm having trouble passing a string from C# and getting it modified by the C function.</p>
  
  <p>Here's the C function:</p>
  
  <pre><code>__declspec(dllexport) void __stdcall Test(char* name)
  {
      *name = "Bar";
  }
  </code></pre>
  
  <p>This is the C# DLL import code:</p>
  
  <pre><code>[DllImport(@"C:/blah/mylibrary.dll")]
  public extern static string Test(string name);
  </code></pre>
  
  <p>This is the code I'm using to call the function:</p>
  
  <pre><code>string s = "foo";
  Test(s);
  //I want s to be "Bar" after the above line
  </code></pre>
  
  <p>I have tried using "ref" and "out" on the string parameter, and tried Marshalling as an LPStr. Depending on what I try, I either get an error like </p>
  
  <blockquote>
    <p>"The pointer passed in as a String must not be in the bottom 64K of the process's address space." </p>
  </blockquote>
  
  <p>or </p>
  
  <blockquote>
    <p>"Attempted to read or write protected memory. This is often an indication that other memory is corrupt." </p>
  </blockquote>
  
  <p>I'm sure I'm just doing something stupid with my pointers. Can someone help me determine the appropriate C# code to get "s" to equal "bar"?</p>
  
  <p>Thank you</p>