On Tuesday, January 24, 2012 23:02:18 Mantis wrote: > 24.01.2012 22:48, Mars пишет: > > Hello everybody. > > I have to convert a char* (from a C function) to long. At the moment > > I'm using > > > >> long foo = to!long( to!string(bar) ); > > > > but this doesn't feel right... with 2 to calls. Is this the way to go? > > Or is there something better? > > > > Mars > > This seems to work: > > char[] c = "123\0".dup; > auto l = parse!long(c); > writeln( l );
Yeah, but note that that's really equivalent to auto foo = to!long(to!(char[])(bar)); except that you're creating an extra variable and using parse with its somewhat different semantics. In either case, you need to convert it from a char* to an actual character array of some kind before converting it to a long, and that means that you're allocating memory. In general, I would recommend just doing what the OP said auto foo = to!long(to!string(bar)); It's the cleanest solution IMHO, and in general, that extra bit of memory allocation isn't a big deal. However, if you know the length of the char*, then you can slice it and pass that to std.conv.to. e.g. auto foo = to!long(bar[0 .. 3]); But you have to know the length of the string already - or use strlen on it to get its length. e.g. auto foo = to!long(bar[0 .. strlen(bar)]); It's quite doable and probably faster than converting to string and then to long, but it's certainly uglier code. This should only be a problem when interfacing with C though, since you really shouldn't be using char*'s or null-terminated strings otherwise. - Jonathan M Davis
