[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?
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With