title: Marshalling wchar_*t via pinvoke in c# does not return its value back to StringBuilder
body: <p>First of all I want to say that I know enough about c++ and pinvoke to be frustrated.</p>
  
  <p>I am currently working on a c++ wrapper and pinvoke that is not returning the info I need.</p>
  
  <p>Below are the pieces of what I am doing:
  I have a c++ method with the signature of:</p>
  
  <pre><code>DllExport int LookupFamilyName(__in PCWSTR familyName,__out_opt wchar_t* result, int lengthIn)
  </code></pre>
  
  <p>With the internal code:</p>
  
  <pre><code>UINT32 count = 0;
  UINT32 length = 0;
  
  LONG rc = GetPackagesByPackageFamily(familyName, &amp;count, NULL, &amp;length, NULL);
  if (rc == ERROR_SUCCESS)
  {
      return int(rc);
  }
  else if (rc != ERROR_INSUFFICIENT_BUFFER)  //122
  {
      return int(rc);
  }
  
  PWSTR *fullNames = (PWSTR *) malloc(count * sizeof(*fullNames));
  
  if (fullNames == NULL)
  {
      return 700010; //faile to allocate memeory
  }
  
  PWSTR buffer = (PWSTR) malloc(length * sizeof(WCHAR));
  if (buffer == NULL)
  {
      return 700011; //faile to allocate memeory
  }
  
  rc = GetPackagesByPackageFamily(familyName, &amp;count, fullNames, &amp;length, buffer);
  
  
  if (rc != ERROR_SUCCESS)
  {
      return int(rc);
  }
  else
  {
      result = new wchar_t[lengthIn];
      for (UINT32 i = 0; i &lt; count; ++i)
      {
          wcscpy_s(result,lengthIn,fullNames[i]);
      }
  }
  free(buffer);
  free(fullNames);
  </code></pre>
  
  <p>I am then using the following to invoke:</p>
  
  <pre><code>    [DllImport("ClassLibrary1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
      public static extern int LookupFamilyName(string familyName, ref StringBuilder sbPackageFullName, int len);
  </code></pre>
  
  <p>And then I am calling it from C# with the following:</p>
  
  <pre><code>string packagename = "Microsoft.MicrosoftEdge_8wekyb3d8bbwe";
  StringBuilder showmethemoney = new StringBuilder(64);
  int x = LookupFamilyName(packagename, ref showmethemoney,showmethemoney.Capacity);
  </code></pre>
  
  <p>I'm passing in a StringBuilder for the wchar_t* and that value is filled in with what I want by the time we get to the end of the LookupFamilyName method but when we get back to the c# code, the StringBuilder does not have the value that the wchar_t* had in the c++ code.</p>
  
  <p>For those of you that know far more then I, what do I need to do to make sure that the the value in the wchar_t* result gets passed back to the StringBuilder?</p>