From the D Blog -- Interfacing D with C: Strings Part One
    Виталий Фадеев 
    vital.fadeev at gmail.com
       
    Wed May 26 04:00:17 UTC 2021
    
    
  
On Monday, 24 May 2021 at 14:02:14 UTC, Mike Parker wrote:
> The blog:
> https://dlang.org/blog/2021/05/24/interfacing-d-with-c-strings-part-one/
>
Good!
toStringz()
Technically we can use 'reserve()' for reserve memory. Possible, 
memory already reserved.
     s.reserve( s.length + 1 );
Then we can set trailing zero.
     s[ $ ] = '\0';
And return pointer.
     return s.ptr;
In this case we prevent memory allocation. Operations will be 
faster.
In other case we cam:
     auto copy = new char[s.length + 1];
     copy[0 .. s.length] = s[];
     copy[s.length] = 0;
     return &assumeUnique(copy)[0];
Example:
     immutable(char)* toStringz( ref string s )
     {
         if ( s.capacity <= s.length )
             s.reserve( s.length + 1 );
         char* cptr = cast( char* ) s.ptr; // C ptr
         char* zptr = cptr + s.length;     // zero ptr
         *zptr = '\0';
         return cast( immutable(char)* ) cptr;
     }
Test code: https://run.dlang.io/is/xZwwtw
    
    
More information about the Digitalmars-d-announce
mailing list