开发者

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

[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 开发者_C百科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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜