www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why aren't wide string literals zero-terminated just like strings?

reply Andrej Mitrovic <none none.none> writes:
Skip the rest of the code until you reach main:
http://codepad.org/zPAgFnPX

We have this notion that string *literals* are zero-terminated, which enables
us to send them to C functions expecting zero-terminated char* strings.

But the same doesn't apply to wide string literals, e.g. "somestring"w. If it
did, its would save quite a bit of typing when calling WinAPI functions that
expect wide strings, instead of having to call "somestring".toUTF16z.

So currently:
immutable(char)[] literal implicitly convertible to const(char)* and char*.
immutable(wchar)[] literal not implicitly convertible to const(wchar)* and
wchar*.
May 18 2011
next sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Wed, 18 May 2011 16:57:37 -0400, Andrej Mitrovic <none none.none> wrote:

 Skip the rest of the code until you reach main:
 http://codepad.org/zPAgFnPX

 We have this notion that string *literals* are zero-terminated, which  
 enables us to send them to C functions expecting zero-terminated char*  
 strings.

 But the same doesn't apply to wide string literals, e.g. "somestring"w.

Yes it does... steves steve-laptop:~/testd$ cat teststringlit.d wstring ws = "abcde"w; steves steve-laptop:~/testd$ ~/dmd-2.053/linux/bin32/dmd -c teststringlit.d steves steve-laptop:~/testd$ ~/dmd-2.053/linux/bin32/obj2asm teststringlit.o .... .rodata segment db 061h,000h,062h,000h,063h,000h,064h,000h ;a.b.c.d. db 065h,000h,000h,000h ;e... .rodata ends ....
 If it did, its would save quite a bit of typing when calling WinAPI  
 functions that expect wide strings, instead of having to call  
 "somestring".toUTF16z.

 So currently:
 immutable(char)[] literal implicitly convertible to const(char)* and  
 char*.
 immutable(wchar)[] literal not implicitly convertible to const(wchar)*  
 and wchar*.

That doesn't make sense... hm... tried it out, definitely a bug. I get the error: teststringlit.d(7): Error: function teststringlit.foo (const(wchar)* widestr) is not callable using argument types (immutable(wchar)[]) teststringlit.d(7): Error: cannot implicitly convert expression ("abcde"w) of type immutable(wchar)[] to const(wchar)* A wstring literal should be able to be passed to a const(wchar)* parameter. So the literal *is* zero terminated, but the compiler isn't letting you pass it directly to a const(wchar)*. Please file with bugzilla. As a workaround, you should be able to do "somestring"w.ptr; -Steve
May 18 2011
prev sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
Ah, I had the wrong assumption but it is a bug. Reported:
http://d.puremagic.com/issues/show_bug.cgi?id=6032

And thanks for disassembling!
May 18 2011