bool FillString(LPWSTR OutName)
LPWSTR out = L"TheName\0";
int len = wcslen(out);
len * sizeof(wchar_t));
[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);
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:
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.