Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to cast wstring to wchar*? (or string to char*)

Tags:

d

[I'm new to D (currently writing my first useful program) and I don't have much C background - just some C# and other mostly pointerless languages.]

Do I need to always append '\0' to the wstring before casting? Is that the only way to ensure that my wchar* will be null-terminated? When it is cast, is it a new copy of the wstring, or does it just get a pointer to the same wstring you're casting?

like image 839
WootenAround Avatar asked Jun 05 '11 11:06

WootenAround


3 Answers

For calling Windows *W functions use http://www.digitalmars.com/d/2.0/phobos/std_utf.html#toUTF16z

Also note that string literals already are 0-terminated so you can pass them directly.

like image 153
Trass3r Avatar answered May 16 '23 03:05

Trass3r


The toStringz functions convert D strings to C-style zero-terminated strings.

immutable(char)* toStringz(const(char)[] s); 
immutable(char)* toStringz(string s);

e.g.

string s;
immutable(char)* cstr = s.toStringz();
//or: toStringz(s);

toStringz allocates a new string on the heap only if the string isn't already null terminated, otherwise it just returns s.ptr.

like image 34
Peter Alexander Avatar answered May 16 '23 03:05

Peter Alexander


If you merely want a pointer, the correct way is to use the 'ptr' property (available for all dynamic arrays, not just strings)

str.ptr

However, if you are wanting something to use with C, to ensure it is nul-terminated, use toStringz

import std.string;
toStringz(str);

toStringz will not perform a copy if the string is already nul terminated.

like image 38
Bernard Avatar answered May 16 '23 04:05

Bernard