A use case for fromStringz

Jacob Carlborg doob at me.com
Fri Apr 1 02:32:42 PDT 2011


On 3/31/11 11:18 PM, Andrej Mitrovic wrote:
> Actually, this still suffers from the problem when the returned char*
> doesn't have a null terminator. It really sucks when C code does that,
> and I've just experienced that. There is a solution though:

In those cases, doesn't the function return the length of the filled 
data or something like that?

> Since we can detect the length of the D array passed into
> `fromStringz`, we can do the job of to!string ourselves and check for
> a null terminator. If one isn't found, we return a string of length 0.
> Here's an updated version which doesn't suffer from the missing null
> terminator problem:
>
> string fromStringz(T)(T value)
> {
>      static if (isArray!T)
>      {
>          if (value is null || value.length == 0)
>          {
>              return "";
>          }
>
>          auto nullPos = value.indexOf("\0");
>
>          if (nullPos == -1)
>              return "";
>
>          return to!string(value[0..nullPos]);
>      }
>      else
>      {
>          return to!string(value);
>      }
> }


-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list