Stefan Steiger
Stefan Steiger

Reputation: 82186

C++ to C# array declaration

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 ?

Upvotes: 1

Views: 748

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

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.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273244

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.

Upvotes: 5

Related Questions