Jump to content
  • Advertisement
Sign in to follow this  
ShockBoy

[.net] Reading arbitrary structures from a stream

This topic is 5408 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The one thing I miss about C++ is the ability to load an entire structure from a file in one function call. I'm trying to load in the header of an MD2 file, which contains 17 integers. Is there any better way than calling ReadInt32 seventeen times? This is the only way I could find, and it uses *gasp* unsafe code and a memory copy. Is there another way that I'm completely missing?
private unsafe MD2Header ReadHeader (BinaryReader br)
{
    MD2Header header = new MD2Header();
    byte* pHeader = (byte*)&header;
    byte[] byteHeader = br.ReadBytes (sizeof(MD2Header));

    for (int i = 0; i < sizeof(MD2Header); i++)
        pHeader = byteHeader;

    return header;
}

Share this post


Link to post
Share on other sites
Advertisement
Look into using the Marshal class to perform the operations. It still requires Security permissions for unmanaged code execution, but you don't need the unsafe and the pointer cast.

Example:


public object Deserialize(byte[] data, Type t)
{
int size = Marshal.SizeOf(t);
IntPtr buf = Marshal.AllocHGlobal(size);
Marshal.Copy(data, 0, buf, size);
object o = Marshal.PtrToStructure(buf, t);
Marshal.FreeHGlobal(buf);

return o;
}



On return, you can cast the object to Type t. There is room for improvement in this code, but it serves it's purpose as an example.


Magius

Share this post


Link to post
Share on other sites
Yeah, I am still looking for something that is done in all safe code and doesn't require any special security.

Maybe I'm just dreaming.

Share this post


Link to post
Share on other sites
The code is technically safe because it still allows the framework to verify the code, meaning it can apply the appropriate code permissions, etc. Aside from reading multiple Int32's, this is the next best option (as far as I am aware).

Magius

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!