C string to D without memory allocation?

Shriramana Sharma via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 20 21:34:07 PST 2015


Hello. I have the following code:

import std.stdio, std.conv;
extern(C) const(char) * textAttrN(const (char) * specString, size_t n);
string textAttr(const(char)[] specString)
{
    const(char) * ptr = textAttrN(specString.ptr, specString.length);
    writeln(ptr);
    return to!string(ptr);
}
void main()
{
    auto s = textAttr("w /g");
    writeln(s.ptr);
}

Now I'm getting different pointer values printed, like:

7F532A85A440
7F532A954000

Is it possible to get D to create a D string from a C string but not 
allocate memory? 

I thought perhaps the allocation is because C does not guarantee 
immutability but a D string has to. So I tried changing the return type of 
textAttr to const(char)[] but I find it is still allocating for the return 
value. Is this because a slice can potentially be appended to but it may 
overflow a C buffer?

Finally, I just want to return a safe D type encapsulating a C string but 
avoid allocation – is it possible or not?

Thanks!

-- 
Shriramana Sharma, Penguin #395953


More information about the Digitalmars-d-learn mailing list