Convert wchar* to wstring?

Kagamin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 5 03:47:28 PDT 2016


On Tuesday, 5 April 2016 at 01:21:55 UTC, Thalamus wrote:
> I am invoking an entry point in a D DLL from C# (via extern 
> (C)), and one of the parameters is a string. This works just 
> fine for ANSI, but I'm having trouble with the Unicode 
> equivalent.
>
> When the message parameter is wchar*, wstring info = 
> to!wstring(message) populates the string with the _address_ of 
> the wchar*. So when message was in the debugger as 
> 0x00000000035370e8 L"Writing Exhaustive unit tests is 
> exhausting.", the wstring info variable ended up as {length=7 
> ptr=0x000000001c174a20 L"35370E8" }. The dstring*/wchar_t* 
> version had equivalent results.

Strings passed from C# are pinned, but temporary. You probably 
want to receive them as immutable (StringBuilder is for mutable 
string buffers), it's also easier to just pass the string length 
from C# side:
C#:
[DllImport(...)]
extern void dfunc(string s, int len);
dfunc(s, s.Length);
D:
extern(C) void dfunc(immutable(wchar)* s, int len)
{
   wstring ws = s[0..len];
}

Since the string is temporary, you'll have to idup it if you want 
to retain it after the call finishes.


More information about the Digitalmars-d-learn mailing list