C string to D without memory allocation?

Jakob Ovrum via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 20 21:40:21 PST 2015

On Monday, 21 December 2015 at 05:34:07 UTC, Shriramana Sharma 
> 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!

Use std.string.fromStringz. to!string assumes that pointers to 
characters are null-terminated strings which is not safe or 
general (unlike std.format, which safely assumes they are 
pointers to single characters); it is a poor design. fromStringz 
is explicit about this assumption.

That said, to!string shouldn't allocate when given 

More information about the Digitalmars-d-learn mailing list