casting and arrays..
Daniel Keep
daniel.keep.lists at gmail.com
Sat Mar 10 20:13:18 PST 2007
gareis wrote:
> Chris Warwick wrote:
>> "Kirk McDonald" <kirklin.mcdonald at gmail.com> wrote in message
>> news:esvk4l$28mi$1 at digitalmars.com...
>>> Chris Warwick wrote:
>>>> "Jarrett Billingsley" <kb3ctd2 at yahoo.com> wrote in message
>>>> news:esvhdv$261a$1 at digitalmars.com...
>>>>> "Chris Warwick" <sp at m.me.not> wrote in message
>>>>> news:esvf5h$2317$1 at digitalmars.com...
>>>>>> std.file.read(filename);
>>>>>>
>>>>>> returns type void[]
>>>> Ok say you have that void[] array returned from std.read.file().
>>>> Whats the best way to copy a struct out from the void array? Only
>>>> way i can think is memcpy, or some heavy duty casting and pointers.
>>>> Is there a cleaner - pretier way with D?
>>>>
>>>> thanks,
>>>>
>>>> cw
>>> Assuming that array.length == YourStruct.sizeof, you can say
>>> cast(YourStruct*)array.ptr
>>> to treat the array as the struct in-place.
>>
>> Well i cant realy do that cause im reading a binary file in, and then
>> i want to parse it, extract structs and various types here and there.
>
> Then you need to do pointer arithmetic, it seems. Assuming your struct
> has a deserializer method that takes a void*:
> ---
> for (int i = 0; i < array.length; i++) {
> if (someStructStartsHere()) {
> someStruct s;
> s.deserialize(array.ptr + i);
> do_stuff_with_someStruct (s);
> }
> }
> ---
>
> That should probably work.
>
>> cheers,
>>
>> cw
>>
>>
Personally, I like std.stream.MemoryStream for things like this. That
way, I don't have to stuff around with pointer arithmetic, and
potentially make a mistake.
Incidentally, I never knew that you could safely cast arrays of one type
to another! Yet another thing I didn't know about D :P
-- Daniel
--
Unlike Knuth, I have neither proven or tried the above; it may not even
make sense.
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d-learn
mailing list