A use case for fromStringz
Andrej Mitrovic
andrej.mitrovich at gmail.com
Thu Mar 31 14:18:07 PDT 2011
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:
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);
}
}
More information about the Digitalmars-d-learn
mailing list