Thread overview
converting c's c* to d strings
Jun 28, 2008
llee
Jun 28, 2008
Xinok
Jun 28, 2008
torhu
Jun 29, 2008
torhu
Jun 29, 2008
novice2
June 28, 2008
Does anyone know how to convert from character array pointers in c to d strings using Phobos?
June 28, 2008
llee wrote:
> Does anyone know how to convert from character array pointers in c to d strings using Phobos? 

You can convert any pointer type to an array type using slicing.

import std.c.string;
char* cstr;
string dstr = cstr[0..strlen(cstr)];
June 28, 2008
Xinok wrote:
> llee wrote:
>> Does anyone know how to convert from character array pointers in c to d strings using Phobos? 
> 
> You can convert any pointer type to an array type using slicing.
> 
> import std.c.string;
> char* cstr;
> string dstr = cstr[0..strlen(cstr)];

Or you can use std.string.toString().  It's cleaner, but slower because it copies the string.

To go the other way, use toStringz().  Or do dstr ~'\0'.

D string literals always have a null terminator appended so you can use them directly with C functions.
June 29, 2008
"torhu" <no@spam.invalid> wrote in message news:g46fa8$1hli$1@digitalmars.com...
> Xinok wrote:
>> llee wrote:
>>> Does anyone know how to convert from character array pointers in c to d strings using Phobos?
>>
>> You can convert any pointer type to an array type using slicing.
>>
>> import std.c.string;
>> char* cstr;
>> string dstr = cstr[0..strlen(cstr)];
>
> Or you can use std.string.toString().  It's cleaner, but slower because it copies the string.

No is isn't, it does the exact same thing as what was posted above (cstr[0 .. strlen(cstr)]).


June 29, 2008
Jarrett Billingsley wrote:
> "torhu" <no@spam.invalid> wrote in message news:g46fa8$1hli$1@digitalmars.com...
>> Xinok wrote:
>>> llee wrote:
>>>> Does anyone know how to convert from character array pointers in c to d strings using Phobos?
>>>
>>> You can convert any pointer type to an array type using slicing.
>>>
>>> import std.c.string;
>>> char* cstr;
>>> string dstr = cstr[0..strlen(cstr)];
>>
>> Or you can use std.string.toString().  It's cleaner, but slower because it copies the string.
> 
> No is isn't, it does the exact same thing as what was posted above (cstr[0 ... strlen(cstr)]). 
> 

Aaaaaaaargh!  It's toStringz that copies the string.  Can't remember the last time I was wrong about anything. :(

In my defence, phobos 2.0 toString(char*) does actually copy...
June 29, 2008
i just want to remember about unicode:
when you pass D char[] to windows API *char
you can use std.windows.charset.toMBSz()

when you pass windows API *char to D char[]
you can use std.windows.charset.fromMBSz()