C string to D without memory allocation?

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 20 21:39:32 PST 2015


On 21/12/15 6:34 PM, Shriramana Sharma wrote:
> 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!

size_t strLen = ...;
char* ptr = ...;

string myCString = cast(string)ptr[0 .. strLen];

I can't remember if it will include the null terminator or not, but if 
it does just decrease strLen by 1.



More information about the Digitalmars-d-learn mailing list