Convert wchar* to wstring?

tcak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 4 21:31:24 PDT 2016


On Tuesday, 5 April 2016 at 01:21:55 UTC, Thalamus wrote:
> I'm sorry for this total newbie question, but for some reason 
> this is eluding me. I must be overlooking something obvious, 
> but I haven't been able to figure this out and haven't found 
> anything helpful.
>
> I am invoking an entry point in a D DLL from C# (via extern 
> (C)), and one of the parameters is a string. This works just 
> fine for ANSI, but I'm having trouble with the Unicode 
> equivalent.
>
> For ANSI, the message parameter is char*, and string info = 
> to!string(message) produces the correct string.
>
> For Unicode, I assumed this would be wchar_t*, as it is in C++. 
> (In C++ you can just pass the wchar_t* value to the wstring 
> constructor.) So I tried wchar_t*, wchar* and dchar* as well. 
> When the message parameter is wchar*, wstring info = 
> to!wstring(message) populates the string with the _address_ of 
> the wchar*. So when message was in the debugger as 
> 0x00000000035370e8 L"Writing Exhaustive unit tests is 
> exhausting.", the wstring info variable ended up as {length=7 
> ptr=0x000000001c174a20 L"35370E8" }. The dstring*/wchar_t* 
> version had equivalent results.
>
> Again, I'm sure I'm missing something obvious, but I poked at 
> this problem with various types, casts, Phobos library string 
> conversions, and I'm just stumped! :)
>
> thanks,
> Thalamus

I cannot give you any code example, but can you try that:

1. By using a loop, calculate the total byte length until finding 
0 (zero). (This would work only if it was given as 
NULL-terminated, otherwise you need to know the length already.)
2. Then define wchar[ calculated_length ] mystring;
3. Copy the content from wchar* into you array. mystring[0 .. 
calculated_length ] = wcharptr[0 .. calculated_length];
4. If you want, you can do casting for your mystring to convert 
it to wstring.


More information about the Digitalmars-d-learn mailing list