TEDSON TEDSON - 6 months ago 51
C# Question

stringbuilder as out parameter

extern "C"
bool FillString(LPWSTR OutName)
LPWSTR out = L"TheName\0";
int len = wcslen(out);
len * sizeof(wchar_t));
return true;

That is function in my c/c++ dll, the following is my call from c#...

[DllImport(@"My.dll", EntryPoint = "FillString", CallingConvention = CallingConvention.Cdecl)]
public static extern bool MyFunction([MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder Name);

var fromdll = new StringBuilder(64);
// I do not know length of out string (Name), but it is null terminated

bool IsFilled = MyFunction(fromdll);


The output is


Can anyone help me to get the output...?



You need to copy one more character. '\0' is called string terminator. Without it C, C++ and PInvoke in .NET do not recognize end of string. If you are copying wcslen characters, zero is not copied. There are many solutions:

  1. Use mentioned wcscpy to copy string with \0
  2. Copy one more character with memcpy(OutName, out, (len + 1) * sizeof(wchar_t)).

Moreover, it's a good idea to pass buffer (StringBuilder) size. C/C++ lets you write outside variable boudaries. This size enables to avoid that.