Convert wchar* to wstring?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 5 12:19:10 PDT 2016


On 05.04.2016 20:44, Thalamus wrote:
> import core.stdc.stddef; // For wchar_t. This is defined differently for
> Windows vs POSIX.
> import core.stdc.wchar_; // For wcslen.

Aside: D has syntax for "// For wchar_t.": `import core.stdc.stddef: 
wchar_t;`.

> wstring toWstring(wchar_t* value)
> {
>      return value ? cast(wstring) value[0..wcslen(wstr)].dup : null;
> }

wchar_t is not wchar. wstring is not (portably) compatible with a 
wchar_t array.

If you actually have a wchar_t* and you want a wstring as opposed to a 
wchar_t[], then you will potentially have to do some converting.

If you have a wchar*, then don't use wcslen, as that's defined in terms 
of wchar_t. There may be some function for finding the first null wchar 
from a wchar*, but I don't know it, and writing out a loop isn't exactly 
hard:

----
wstring toWstring(const(wchar)* value)
{
     if (value is null) return null;
     auto cursor = value;
     while (*cursor != 0) ++cursor;
     return value[0 .. cursor - value].dup;
}
----


More information about the Digitalmars-d-learn mailing list