what's the right way to get char* from string?

pineapple via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 5 02:53:30 PDT 2016


On Thursday, 5 May 2016 at 07:49:46 UTC, aki wrote:
> Hello,
>
> When I need to call C function, often need to
> have char* pointer from string.

This might help:

import std.traits : isSomeString;
import std.string : toStringz;

extern (C) int strcmp(char* string1, char* string2);

int strcmpD0(S)(in S lhs, in S rhs) if(is(S == string) || is(S == 
const(char)[])) { // Best
     return strcmp(
         cast(char*) toStringz(lhs),
         cast(char*) toStringz(rhs)
     );
}
int strcmpD1(S)(in S lhs, in S rhs) if(is(S == string) || is(S == 
const(char)[])) { // Works
     return strcmp(
         cast(char*) lhs.ptr,
         cast(char*) rhs.ptr
     );
}

/+
int strcmpD2(S)(in S lhs, in S rhs) if(is(S == string) || is(S == 
const(char)[])) { // Breaks
     return strcmp(
         toStringz(lhs),
         toStringz(rhs)
     );
}
+/

void main(){
     import std.stdio;
     writeln(strcmpD0("foo", "bar")); // Best
     writeln(strcmpD1("foo", "bar")); // Works
     //writeln(strcmpD2("foo", "bar")); // Breaks
}




More information about the Digitalmars-d-learn mailing list