shd:
> I'm having a problem in passing a value to char* expecting function
> in D 2.0. Already tried:
> to!(char*)("my string");

A solution, maybe correct:


import std.string: toStringz, indexOf;
import std.c.string: strlen;
import std.stdio: writeln;

void main() {
    string s = "my string";
    assert(indexOf(s, '\0') == -1); // useful
    char* p = cast(char*)toStringz(s);
    writeln(strlen(p));
}


But keep in mind this string p is managed by the D GC.

That cast to cast(char*) is not nice.

There is no need to dup the string given to toStringz because it performs the 
dup internally (wasting a initialization of 'copy'), this is the cleaned up 
implementation of toStringz:


const(char)* toStringz(string s) {
    char[] copy = new char[s.length + 1];
    copy[0 .. s.length] = s;
    copy[s.length] = 0;
    return copy.ptr;
}


I don't know why it returns a const(char)* instead of a char*. Do you know why?

Bye,
bearophile

Reply via email to