2013-04-17 75 views
2

我正在將C代碼移植到C#,並且我有一些疑惑。將C結構移植到C#

考慮這樣的結構:

typedef struct 
{ 
    uint32_t  w; 
    uint32_t  h; 
    uint32_t  f_cc; 
    uint32_t  st; 
    unsigned char *pl[4]; 
    int32_t  strd[4]; 
    void   (*done)(void *thisobj); 
    void   *e_cc; 
    uint32_t  rsrvd2; 
    uint32_t  rsrvd3; 
} f_tt; 

我已經做到了這一點,它不工作(可能是因爲它是錯的: - /):

[StructLayout(LayoutKind.Sequential, Pack = 1)] 
public struct f_tt 
{ 
    public uint w; 
    public uint h; 
    public uint f_cc; 
    public uint st; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] 
    public Byte[] pl; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] 
    public int[] strd; 
    public delegate void done(IntPtr thisobj); 
    public delegate void e_cc(); 
    public uint rsrvd2; 
    public uint rsrvd3; 
} 

有人能告訴我如何做到這一點我知道了#?

void   (*done)(void *thisobj); 
    void   *e_cc; 

謝謝!

+0

如果它沒有涉及到指針,你應該在大多數情況下使用'IntPtr'。 –

+1

你可以給出一些關於'pl'中'byte *'的語義是什麼的信息嗎?特別是如果它們指向單個字節,則空終止字符串,某個固定大小的數組...,...哼。猜猜這些是每個顏色分量的4個指針 – CodesInChaos

回答

4

在我們來到代表之前,我懷疑你打包結構是錯誤的。這樣做非常不尋常。只有在C代碼中找到包#pragma時才這樣做。

e_cc字段不是函數指針。這只是一個無效的指針。在C#中是IntPtr

pl成員是4個指針的數組。我不太清楚它們包含的內容,但是可以肯定,你可以封送這樣的:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] 
public IntPtr[] pl; 

這使得你與人工干預來填充陣列,或閱讀其內容。這可能是由編組人員完成的,但是如果不知道互操作的語義,我不能說如何做到這一點。

至於done,您應該在結構之外聲明委託。就像這樣:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)] 
public delegate void doneDelegate(IntPtr thisobj); 

在這裏,我假設調用約定cdecl,因爲沒有什麼在C代碼,否則說。

全部放在一起你:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)] 
public delegate void doneFunc(IntPtr thisobj); 

[StructLayout(LayoutKind.Sequential)] 
public struct f_tt 
{ 
    public uint w; 
    public uint h; 
    public uint f_cc; 
    public uint st; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] 
    public IntPtr[] pl; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] 
    public int[] strd; 
    public doneDelegate done; 
    public IntPtr e_cc; 
    public uint rsrvd2; 
    public uint rsrvd3; 
} 
+0

「pl」部分是否正確?看起來像是一串4個指向我的指針。 – CodesInChaos

+0

IIRC,指針在x64中是8個字節,所以你認爲這個代碼只能在x86上運行? (btw爲什麼不使用'byte'而不是'Byte') –

+0

@CodesInChaos不,錯過了一個指針。我需要看看。 –