reading "binary struct"

P

Pawe³

Hi!
I want to read with C# some binary file with well defined binary structure.
In C++ I was declaring appropriate struct, like:

typedef struct {BYTE b1; WORD w1, w2; DWORD dw1} REKORD1;
REKORD1 buff ;

and then read record from file with
read (file, (void *) &buff, sizeof (REKORD1));

Is this technique possible with C#? Now I have to "manually" bond together
particular values with ReadByte().

Thanks for any help
Paul
 
M

Morten Wennevik

Hi Paul,

It is possible with C# to load a byte array into a struct with something like

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct REKORD1
{
public byte b1;
public ushort w1;
public ushort w2;
public uint dw1;
}

....

byte[] data = GetData(); // read from file or something
int size = Marshal.SizeOf(typeof(REKORD1);

IntPtr ip = Marshal.AllocHGlobal(size);
GCHandle gch = GCHandle.Alloc(ip, GCHandleType.Pinned);

Marshal.Copy(data, 0, ip, size);
REKORD1 newRecord = (REKORD1)Marshal.PtrToStructure(ip, t);

gch.Free();
Marshal.FreeHGlobal(ip);
 
B

BMermuys

Hi,
inline

Pawe³ said:
Hi!
I want to read with C# some binary file with well defined binary
structure.
In C++ I was declaring appropriate struct, like:

typedef struct {BYTE b1; WORD w1, w2; DWORD dw1} REKORD1;
REKORD1 buff ;

and then read record from file with
read (file, (void *) &buff, sizeof (REKORD1));

Is this technique possible with C#? Now I have to "manually" bond together
particular values with ReadByte().

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct REKORD1
{
byte b1;
ushort w1;
ushort w2;
uint dw1;
}

byte[] data; // read from file
GCHandle gData = GCHandle.Alloc(data, GCHandleType.Pinned);
REKORD1 newRecord =
(REKORD1)Marshal.PtrToStructure(gData.AddrOfPinnendObject(),
typeof(REKORD1));
gch.Free();


HTH,
greetings
 
B

BMermuys

Hi

Morten Wennevik said:
Hi Paul,

It is possible with C# to load a byte array into a struct with something
like

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct REKORD1
{
public byte b1;
public ushort w1;
public ushort w2;
public uint dw1;
}

...

byte[] data = GetData(); // read from file or something
int size = Marshal.SizeOf(typeof(REKORD1);

IntPtr ip = Marshal.AllocHGlobal(size);
//GCHandle gch = GCHandle.Alloc(ip, GCHandleType.Pinned);

Marshal.Copy(data, 0, ip, size);
REKORD1 newRecord = (REKORD1)Marshal.PtrToStructure(ip, t);

//gch.Free();
Marshal.FreeHGlobal(ip);

You allocate memory on the heap and then you pin it ? Memory obtained from
the unmanaged heap (AllocHGlobal) does not need pinning.
If you pin the byte array you can get a pointer to it and then use that for
PtrToStructure().


greetings
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top