473,706 Members | 4,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing Structures To Binary Files

I am porting an application from C++ to C#, and am having trouble finding a way to quickly and efficiently write structures to a binary file. In C++ this is trivial because all that is necessary is to pack the structure to 1 byte boundries, and then just write out the structure directly to the File IO function

pragma pack (1

typedef struct
char var1[4]
int var1
}MyStruc

fwrite(&myStruc ture,sizeof(MyS truct),1,filepo inter);
Things are clearly different in C# however(and .NET in general). I am using a FileStream(with a 4k buffer for maximum file performance) and it only writes byte arrays. So I think the only issue is how to efficiently turn a structure into a byte array

I know one can marshall the data into a byte array like so

[StructLayout(La youtKind.Sequen tial, Pack = 1)
public struct MyStruc

[MarshalAs(Unman agedType.ByValA rray, SizeConst=4)]
public char[] var1;
public int var2
public class ByteManipulatio

/// <summary
/// Marshals data from an object to an array of bytes
/// </summary
/// <param name="obj">The object to be serialized</param
/// <returns>Arra y of bytes</returns
public static byte[] SerializeObject ToBytes(object obj

int size = Marshal.SizeOf( obj );
IntPtr buffer = Marshal.AllocHG lobal( size );
Marshal.Structu reToPtr( obj, buffer, false );
byte[] data = new byte[ size ];
Marshal.Copy( buffer, data, 0, size );
Marshal.FreeHGl obal( buffer );
return data

but this has 2 problems for my application, 1 it is slow, and 2, it does not work because the Marshall.Sizeof () call fails because of the arrays in the structure (even with the MarshallAs attribute, it compiles fine but I get a runtime error

It would be preferable performance wise for me to use an unsafe block

unsaf

fixed(byte *pData = *(byte*)myStruc t

but I keep getting an error that I cannot convert MyStruct to byte*.

Am I casting wrong in the unsafe block? There has to be a way to do this. All I want to do is get myStruct into a byte[]..

Also, I know one can use serialization to stuff objects into binary files, but I am unsure of the formatting effects of the serialization formatter. I need to control the format of the binary file - does the serialization add bytes to the file in any way that would confilct with a well defined file format

Thank you in advance for your help
Nov 16 '05 #1
2 7806
phyzics wrote:
unsafe
{
fixed(byte *pData = *(byte*)myStruc t)
{

}
}

but I keep getting an error that I cannot convert MyStruct to byte*.

You need a pointer of myStruct first, to convert it to byte*. Try using

\\\
fixed(byte *pData = (byte*)&myStruc t)
///
which would be the C++-way to do this but as I've never worked in C#
unsafe mode I can't say if that'll do it.

--
Konrad -
http://madrat.net/
Nov 16 '05 #2
Thanks for your reply, but this does not work:

the following code results in an error

unsafe
fixed(byte *pData = (byte*)&myStruc t
that states that the right hand side cannot be a cast expression. Ok, so I'll try not typecasting..

unsafe
fixed(byte *pData = &myStruct
This generates an error that states that MyStruct cannot implicitly be converted to byte*

Any suggestions to go from here

----- Konrad L. M. Rudolph wrote: ----

phyzics wrote
unsaf

fixed(byte *pData = *(byte*)myStruc t

but I keep getting an error that I cannot convert MyStruct to byte*.

You need a pointer of myStruct first, to convert it to byte*. Try usin

\\ fixed(byte *pData = (byte*)&myStruc t
//
which would be the C++-way to do this but as I've never worked in C#
unsafe mode I can't say if that'll do it

--
Konrad
http://madrat.net/
Nov 16 '05 #3

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

Similar topics

6
23599
by: Sebastian Kemi | last post by:
How should a write a class to a file? Would this example work: object *myobject = 0; tfile.write(reinterpret_cast<char *>(myobject), sizeof(*object)); / sebek
5
5560
by: rob | last post by:
hey every1, I've got alot of data to write out to file and it's all just 1's and 0's. It's all stored in 2 dimensional arrays of width 32 and varying height. At the moment it's all just integer arrays and the individual 1's and 0's are being written out as integers.
10
3290
by: Kristian Nybo | last post by:
Hi, I'm writing a simple image file exporter as part of a school project. To implement my image format of choice I need to work with big-endian bytes, where 'byte' of course means '8 bits', not 'sizeof(char)'. It seems that I could use bitset<8> to represent a byte in my code --- if you have a better suggestion, I welcome it --- but that still leaves me with the question of how to write those bitsets to an image file as big-endian bytes...
2
1766
by: DBC User | last post by:
Hi Sharpies, I have a C program I am converting it into C#. Everything is fine except this process creates a 6K byte binary file. This file initially filled with 6K null and then start populating only the fields with value in specified locations(3 seperate structures). The way the C does is by creating a structures, which will be filled with null initially. Then selectivly populating only the fields with values and only up to the length...
7
6061
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should populate a series of structures of specified variable composition. I have the structures created OK, but actually reading the files is giving me an error. Can I ask a simple question to start with: I'm trying to read the file using the...
3
18960
by: nicolasg | last post by:
Hi, I'm trying to open a file (any file) in binary mode and save it inside a new text file. After that I want to read the source from the text file and save it back to the disk with its original form. The problem is tha the binary source that I extract from the text file seems to be diferent from the source I saved. Here is my code: 1) handle=file('image.gif','rb')
3
3437
by: Zeke Zinzul | last post by:
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;
6
5269
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;
3
11152
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 obviously have my head up and locked when it comes to C#. My first attempt to read such a file was something like: myBinaryReader.ReadBytes(sizeof(myStructArray));
0
9282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9154
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9048
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6614
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5937
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4445
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4708
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3142
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2089
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.