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

aki via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 5 00:49:46 PDT 2016


Hello,

When I need to call C function, often need to
have char* pointer from string.

"Interfacing to C++" page:
https://dlang.org/spec/cpp_interface.html
have following example.

extern (C) int strcmp(char* string1, char* string2);
import std.string;
int myDfunction(char[] s)
{
     return strcmp(std.string.toStringz(s), "foo");
}

but this is incorrect because toStringz() returns immutable 
pointer.
One way is to write mutable version of toStringz()

char* toStringzMutable(string s) @trusted pure nothrow {
     auto copy = new char[s.length + 1];
     copy[0..s.length] = s[];
     copy[s.length] = 0;
     return copy.ptr;
}

But I think this is common needs,
why it is not provided by Phobos?
(or tell me if it has)

Thanks,
aki



More information about the Digitalmars-d-learn mailing list