Filling Structs.

M

MSDousti

Hello

I want to write a C# (or VB.NET) program which reads the structure of
a PE (odinary win32 executable) file. These files have a long header
(512 bytes or so). The definition of the header exists in WINNT.h file
(you can see many "struct"s there).



Here comes my problem: how can I read a file and "fill" the structs?
Note that a method such as FileStream.Read can only fill an array not
a struct:



public override int Read(

in byte[] array,

int offset,

int count

);



The conversion from an array to those structs is really cumbersome. In
an unmanaged language, I could use pointers to have the array and the
struct share the same memory, thus filling the struct members with
array's values. But, in this managed context, that's not the case.



Any help is appreciated.

PS: If possible, I want to write a program without "unsafe" blocks or
Windows API functions.



thnx in advance,

MSD.
 
M

MSDousti

Mattias Sjögren said:
With a BinaryReader you can fill the struct member by member.



Mattias

Hi Mattias, thnx 4 answering.
That was the thing I once thought about, but there's a big problem to
this solution. If I'd wanted to fill one struct many times, I should
have written a BinaryReader. But I have to fill many structs just
once, so it's not worth writing a BinaryReader for each one.

Another solution I may come across, is using
[StructLayout(LayoutKind.Sequential, Pack = 0)]
attribute for my struct. I think because the fields place in memory
sequentially, there must be some way to access them in order.

However, thnx again.
It'll great of u if u answer me again.
& sorry for gramatical errors.

MSD.
 
D

Dennis Myrén

If you redefine the struct in your code, you may do something like this.

using System.Runtime.InteropServices;

Stream input = new FileStream(...);
byte [] buff = new byte [Marshal.SizeOf(HEADER)];
input.Read(buff, 0x0, buff.Length);
IntPtr ptr = Marshal.AllocHGlobal(buff.Length);
Marshal.Copy(buff, 0x0, ptr, buff.Length);
HEADER header = (HEADER) Marshal.PtrToStructure(ptr, typeof(HEADER));
Marshal.FreeHGlobal(ptr);


[ StructLayout( LayoutKind.Sequential, Pack = 0x1 ) ]
struct HEADER
{
....
}
 

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