473,398 Members | 2,393 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Reading / Writing Data into / out of a C# Structure

Hi Guys & Geeks,

What's the most elegant way of dealing with binary data and structures?

Say I have this (which I actually do, a woo-hoo):

struct Struct_IconHeader
{
byte width;
byte height;
byte colorcount;
byte reserved;
UInt16 planes;
UInt16 bitcount;
UInt64 sizeinbytes;
UInt64 fileoffset;
}

....

more structures declared, including a master structure encompassing all
preceding structures.

Do I really have to do this:

IconData.IconHeader.width=br.ReadByte();
IconData.IconHeader.height=br.ReadByte();
IconData.IconHeader.colorcount=br.ReadByte();
IconData.IconHeader.reserved=br.ReadByte();
IconData.IconHeader.planes=br.ReadUInt16();
IconData.IconHeader.bitcount=br.ReadUInt16();
IconData.IconHeader.sizeinbytes=br.ReadUInt64();
IconData.IconHeader.fileoffset=br.ReadUInt64();

?

Is there some elegant way of just doing:

br.Read(IconData);

When I try: br.Read(IconData,0,Marshal.SizeOf(IconData));

I am getting a casting (director) error about being unable to convert blah
to chars[].

I am hoping that I am ignorant (it can be blissful) and .NET provides a
_simple_ way of reading binary data into structures.

Thank you very much,

Zeke
Jun 30 '06 #1
3 3396
Zeke,

You could read the bytes into an array, and then use the static
BlockCopy method on the Buffer class to copy the bytes into your structure.
Basically, you have an array of bytes, and an array of one of your
structures.

If you have a handle to the file, you could use unsafe code with a call
to the ReadFile/ReadFileEx API function. Instead of passing in a byte array
to read into the buffer, you can pass a pointer to your structure, and then
have it read directly into that.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Zeke Zinzul" <ze**@shambolica.demon.co.uk> wrote in message
news:e8*******************@news.demon.co.uk...
Hi Guys & Geeks,

What's the most elegant way of dealing with binary data and structures?

Say I have this (which I actually do, a woo-hoo):

struct Struct_IconHeader
{
byte width;
byte height;
byte colorcount;
byte reserved;
UInt16 planes;
UInt16 bitcount;
UInt64 sizeinbytes;
UInt64 fileoffset;
}

...

more structures declared, including a master structure encompassing all
preceding structures.

Do I really have to do this:

IconData.IconHeader.width=br.ReadByte();
IconData.IconHeader.height=br.ReadByte();
IconData.IconHeader.colorcount=br.ReadByte();
IconData.IconHeader.reserved=br.ReadByte();
IconData.IconHeader.planes=br.ReadUInt16();
IconData.IconHeader.bitcount=br.ReadUInt16();
IconData.IconHeader.sizeinbytes=br.ReadUInt64();
IconData.IconHeader.fileoffset=br.ReadUInt64();

?

Is there some elegant way of just doing:

br.Read(IconData);

When I try: br.Read(IconData,0,Marshal.SizeOf(IconData));

I am getting a casting (director) error about being unable to convert blah
to chars[].

I am hoping that I am ignorant (it can be blissful) and .NET provides a
_simple_ way of reading binary data into structures.

Thank you very much,

Zeke

Jun 30 '06 #2
> You could read the bytes into an array, and then use the static
BlockCopy method on the Buffer class to copy the bytes into your structure.
Basically, you have an array of bytes, and an array of one of your
structures.


Buffer.BlockCopy only works on arrays of primitive value types, not
structs.

Personally I would do it the way Zeke is already, with a BinaryReader,
but hide the Read calls in a constructor on the struct.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Jun 30 '06 #3
do you want to convert the structure to a byte array and vice versa ?

then look into the code below

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;

namespace WindowsApplication2
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public static byte[] RawSerialize( object anything )
{
int rawsize = Marshal.SizeOf( anything );
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.StructureToPtr( anything, buffer, false );
byte[] rawdatas = new byte[ rawsize ];
Marshal.Copy( buffer, rawdatas, 0, rawsize );
Marshal.FreeHGlobal( buffer );
return rawdatas;
}

public static object RawDeserialize( byte[] rawdatas, Type anytype )
{
int rawsize = Marshal.SizeOf( anytype );
if( rawsize rawdatas.Length )
return null;
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.Copy( rawdatas, 0, buffer, rawsize );
object retobj = Marshal.PtrToStructure( buffer, anytype );
Marshal.FreeHGlobal( buffer );
return retobj;
}

[StructLayout(LayoutKind.Sequential,Pack=1)]
public struct test
{
public byte a;
public byte b;
public byte c;
public byte d;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=6)] public byte[]
Reserved;
}

[StructLayout(LayoutKind.Sequential,Pack=1)]
public struct test2
{
public byte a;
string ms;
}

// sample usage:
[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
struct YourStruct
{
public Int32 First;
public Int32 Second;
[MarshalAs( UnmanagedType.ByValTStr, SizeConst=16 )]
public String Text;
}

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(56, 69);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(292, 28);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
//
// label2
//
this.label2.Location = new System.Drawing.Point(55, 113);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(300, 23);
this.label2.TabIndex = 1;
this.label2.Text = "label2";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(430, 369);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)
{
test mytest=new test();

mytest.a=10;
mytest.b=100;
mytest.c=210;

label1.Text=Marshal.SizeOf(mytest).ToString();

test2 mytest2=new test2();

label2.Text=Marshal.SizeOf(mytest2).ToString();

byte[] a=RawSerialize( mytest );

test mytest3=(test)RawDeserialize( a, typeof(test));

}
}
}

"Zeke Zinzul" <ze**@shambolica.demon.co.ukwrote in message
news:e8*******************@news.demon.co.uk...
Hi Guys & Geeks,

What's the most elegant way of dealing with binary data and structures?

Say I have this (which I actually do, a woo-hoo):

struct Struct_IconHeader
{
byte width;
byte height;
byte colorcount;
byte reserved;
UInt16 planes;
UInt16 bitcount;
UInt64 sizeinbytes;
UInt64 fileoffset;
}

...

more structures declared, including a master structure encompassing all
preceding structures.

Do I really have to do this:

IconData.IconHeader.width=br.ReadByte();
IconData.IconHeader.height=br.ReadByte();
IconData.IconHeader.colorcount=br.ReadByte();
IconData.IconHeader.reserved=br.ReadByte();
IconData.IconHeader.planes=br.ReadUInt16();
IconData.IconHeader.bitcount=br.ReadUInt16();
IconData.IconHeader.sizeinbytes=br.ReadUInt64();
IconData.IconHeader.fileoffset=br.ReadUInt64();

?

Is there some elegant way of just doing:

br.Read(IconData);

When I try: br.Read(IconData,0,Marshal.SizeOf(IconData));

I am getting a casting (director) error about being unable to convert blah
to chars[].

I am hoping that I am ignorant (it can be blissful) and .NET provides a
_simple_ way of reading binary data into structures.

Thank you very much,

Zeke


Jul 1 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Santah | last post by:
hi I'm new to C++ and I'm currently working on Visual C++ 6.0 I'm trying to open a text file, and read some data from it part of the text file looks like this: --------
1
by: RML | last post by:
Hi, I have a MFC C++ application which write the data in a structure out to a file. Here is the structure... typdef struct { short ID; TCHAR Num; short x; } TestStruct;
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
111
by: Tonio Cartonio | last post by:
I have to read characters from stdin and save them in a string. The problem is that I don't know how much characters will be read. Francesco -- ------------------------------------- ...
16
by: Jm.GlezdeRueda | last post by:
Hi all, Im trying to read a 24bit bmp with fread, and i have some problems.. I want to read the whole structure in one time, but i dont know why, it only reads the first member well.. I have...
9
by: Bill Woessner | last post by:
Suppose I have a structure, foo, which is a POD. I would like to read and write it to disk as follows: std::ofstream outs; foo bar; outs.write(reinterpret_cast<char*>(&bar), sizeof(foo));...
6
by: John | last post by:
Hi I am trying to save settings of controls on my form to a file so I can read them back later and recreate the controls on the form. I have figured out how to go through all controls and get...
6
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features...
3
by: =?Utf-8?B?UmF5IE1pdGNoZWxs?= | last post by:
Hello, I'm trying to write an array of structures named myStructArray to a binary file and later on read it back. Although I could complete the entire project in C in about 2 minutes, I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.