views:

104

answers:

2

I want to convert the below code to C#:

struct Elf32_Ehdr {
  uint8   e_ident[16];   // Magic number and other info
  uint16  e_type;        // Object file type
  uint16  e_machine;     // Architecture
  uint32  e_version;     // Object file version
  uint32  e_entry;       // Entry point virtual address
  uint32  e_phoff;       // Program header table file offset
  uint32  e_shoff;       // Section header table file offset
  uint32  e_flags;       // Processor-specific flags
  uint16  e_ehsize;      // ELF header size in bytes
  uint16  e_phentsize;   // Program header table entry size
  uint16  e_phnum;       // Program header table entry count
  uint16  e_shentsize;   // Section header table entry size
  uint16  e_shnum;       // Section header table entry count
  uint16  e_shstrndx;    // Section header string table index
};

Apparently, it maps to different casing. uint16 -> UInt16
uint32 -> UInt32
uint64 -> UInt64

And apparently, uint8 maps to Byte.

The problem is:

Byte   e_ident[16];   // Magic number and other info<br />


won't compile, it says: Array size cannot be declared in variable declaration...

What, no fixed size array without new?

Is that correct to map it to this:

Byte[] e_ident = new Byte[16];   // Magic number and other info



or will that turn out to be entirely wrong ?

+4  A: 

You will need the Structlayout and MarshalAs attributes, and use it something like:

//untested
[Structlayout]
struct Elf32_Ehdr 
{
  [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
  Byte   e_ident[16];   // Magic number and other info
  Uint16  e_type;       // Object file type
  ...
}

But consider this a hint for further searching, it's not something I know a lot about.

Henk Holterman
It doesn't compile, yet the highest voted answer. Odd place, isn't it?
Hans Passant
@Hans, it was from memory, that's what the //untested flag is for. I never claimed/pretended it compiled. It seems to work as a pointer though. And you were simply 3 hours late (-:.
Henk Holterman
I know, kinda grumpy this afternoon. Deleted a bunch of good answers, stuff that compiled. Sorry!
Hans Passant
+2  A: 

You should use a fixed-size buffer - although this requires the structure to be declared in unsafe code:

unsafe struct Elf32_Ehdr
{
    fixed byte e_ident[16];
    ushort type;
    // etc
}

You may also need [StructLayout(StructLayoutKind.Sequential)] or [StructLayout(StructLayoutKind.Explicit)]. Basically the fixed-size buffer makes sure that the data is inline, rather than creating a separate array which needs cunning marshalling.

Jon Skeet