fromStringz for wide characters

John Burton via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 5 05:19:32 PDT 2017


On Tuesday, 5 September 2017 at 08:39:37 UTC, Jonathan M Davis 
wrote:
> On Tuesday, September 05, 2017 08:15:04 John Burton via 
> Digitalmars-d-learn wrote:
>> std.string.fromStringz will create me a string from a null 
>> terminated array of characters. But I have a zero terminated 
>> array of "short"s (from a win32 api call) which I'd like to 
>> turn into a wstring. But there doesn't seem to be a function 
>> to do this.
>>
>> Do I need to write my own, or am I missing something?
>
> I'm fairly certain that to!wstring will do it, but it will 
> definitely allocate, whereas fromStringz just slices what it's 
> given. I don't think that there's currently a wchar equivalent 
> to fromStringz, but it would be pretty trivial to write if you 
> didn't want to use to!wstring. fromStringz is just
>
>     return cString ? cString[0 .. strlen(cString)] : null;
>
> and all you'd have to do would be to replace strlen with wcslen 
> from core.stdc.wchar_. There's a decent chance that you'll want 
> to allocate the string though, in which case to!wstring would 
> be the right choice.

Thank you. I wanted something that didn't allocate in this case. 
The underlying storage will be kept for other reasons so I might 
as well have a string that just refers to the data contained in 
it.
I had done something like you suggested, but wondered if I'd 
missed something given the existence of a function for byte 
strings.





More information about the Digitalmars-d-learn mailing list