Converting from std.file.read's void[]
Steven Schveighoffer
schveiguy at yahoo.com
Wed Sep 22 06:37:57 PDT 2010
On Tue, 21 Sep 2010 19:06:43 -0400, Jonathan M Davis <jmdavisProg at gmx.com>
wrote:
> Okay, it seems that the way to read in a binary file is to use
> std.file.read()
> which reads in the file as a void[]. This immediately raises the
> question as to
> how to convert the void[] into something useful. It seems to me that
> casting
> void[] to a ubyte[] is then the appropriate thing to do because then
> you can
> properly index it and grab the appropriate bytes that need to be
> converting into
> useful values. However, that still raises the question of how to get
> anything
> useful out of the bytes. UTF-8 strings are easy because they're the same
> size as
> ubytes. Casting to char[] for the portion of the data that you want as a
> string
> seems to work just fine. But what about other types? Is it the correct
> thing to
> cast to T[] where T is whatever type the data represents and then index
> into it
> to get the values that you want of that type and then cast the next
> section of
> the data to U[] where U is the type for the next section of the data,
> etc.? Or
> is there a better way to handle this?
You can slice void arrays, even though you cannot index them. If you know
for instance that a struct S resides at the 15th byte, you can do:
(cast(S[])arr[15..$])[0];
or:
*(cast(S*)arr.ptr + 15);
there are various ways to get the data. Only if you know the data is an
*array* of a certain type is it useful to cast the entire array.
-Steve
More information about the Digitalmars-d-learn
mailing list