Convert wchar* to wstring?
Thalamus via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Apr 5 11:44:48 PDT 2016
On Tuesday, 5 April 2016 at 11:26:44 UTC, Thalamus wrote:
> Thanks everyone! You've all been very helpful.
For anyone who has the same question and happens on this thread,
I wanted to post what I finally came up with. I combined the
information everyone in this thread gave me with what I saw in
Phobos source for the to!string() implementation, closely
following the latter. The important to!string() code is in the
toImpl implementation in conv.d at line 880. The existing code
uses strlen, but that's an ANSI function. Fortunately, D has
wcslen available, too.
import core.stdc.stddef; // For wchar_t. This is defined
differently for Windows vs POSIX.
import core.stdc.wchar_; // For wcslen.
wstring toWstring(wchar_t* value)
{
return value ? cast(wstring) value[0..wcslen(wstr)].dup :
null;
}
The Phobos code notes that this operation is unsafe, because
there's no guarantee the string is null-terminated as it should
be. That's definitely true. The only outcome you can be really
sure is accurate is an access violation. :)
thanks!
Thalamus
More information about the Digitalmars-d-learn
mailing list