On Thu, 05 May 2016 07:49:46 +0000
aki via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com> wrote:

> 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)

If you want a different mutability, then use the more general function
std.utf.toUTFz. e.g. from the documentation:

    auto p1 = toUTFz!(char*)("hello world");
    auto p2 = toUTFz!(const(char)*)("hello world");
    auto p3 = toUTFz!(immutable(char)*)("hello world");
    auto p4 = toUTFz!(char*)("hello world"d);
    auto p5 = toUTFz!(const(wchar)*)("hello world");
    auto p6 = toUTFz!(immutable(dchar)*)("hello world"w);

- Jonathan M Davis

Reply via email to