473,473 Members | 1,816 Online
Bytes | Software Development & Data Engineering Community
Create 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(&myStructure,sizeof(MyStruct),1,filepointer );
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(LayoutKind.Sequential, Pack = 1)
public struct MyStruc

[MarshalAs(UnmanagedType.ByValArray, 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>Array of bytes</returns
public static byte[] SerializeObjectToBytes(object obj

int size = Marshal.SizeOf( obj );
IntPtr buffer = Marshal.AllocHGlobal( size );
Marshal.StructureToPtr( obj, buffer, false );
byte[] data = new byte[ size ];
Marshal.Copy( buffer, data, 0, size );
Marshal.FreeHGlobal( 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*)myStruct

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 7784
phyzics wrote:
unsafe
{
fixed(byte *pData = *(byte*)myStruct)
{

}
}

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*)&myStruct)
///
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*)&myStruct
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*)myStruct

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*)&myStruct
//
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
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
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...
10
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...
2
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...
7
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...
3
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...
3
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...
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;
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
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
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...
1
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
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
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...

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.