2010-08-15 110 views
1

欲下面的代碼轉換爲C#:C++到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 
}; 

顯然,它映射到不同的套管。 UINT16 - > UINT16
UINT32 - > UInt32的
UINT64 - > UINT64

而顯然,UINT8映射到字節。

的問題是:

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


不會編譯,它說:數組大小不能在變量聲明中聲明...

什麼,沒有固定的大小數組沒有新的?

這是否正確將其映射到這一點:

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



或將是被證明是完全錯誤的?

回答

5

您將需要Structlayout和屬性的MarshalAs,並使用它是這樣的:

//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 
    ... 
} 

但認爲這對於進一步搜索的提示,它不是東西,我知道很多有關。

+0

它不編譯,但最高的投票答案。奇怪的地方,不是嗎? – 2010-08-18 21:26:22

+0

@Hans,這是來自記憶,這是//未經測試的旗幟。我從來沒有聲稱/假裝它編譯。它似乎是作爲一個指針工作。而且你只遲了3個小時( - : 。 – 2010-08-18 21:42:55

+0

我知道,今天下午有點脾氣暴躁,刪掉了一堆很好的答案,編譯的東西,對不起! – 2010-08-18 21:45:43

3

您應該使用fixed-size buffer - 儘管這需要在不安全的代碼中聲明結構:

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

您可能需要[StructLayout(StructLayoutKind.Sequential)][StructLayout(StructLayoutKind.Explicit)]。基本上固定大小的緩衝區確保數據是內聯的,而不是創建需要狡猾編組的單獨數組。