如何在C#中编组这个嵌套的,可变长度的C结构

时间:2014-11-28 10:30:37

标签: c# c pinvoke marshalling

typedef struct pt_bir {
    PT_BIR_HEADER Header;
    BYTE Data[1]; //variable length based on pt_bir_header.Length
} PT_BIR

typedef struct pt_bir_header {
    DWORD Length;
    BYTE HeaderVersion;
    BYTE Type;
    WORD FormatOwner;
    WORD FormatID;
    CHAR Quality;
    BYTE Purpose;
    DWORD FactorsMask;
} PT_BIR_HEADER

我的C函数是:

PT_STATUS LoadFinger (
    IN PT_CONNECTION hConnection,
    IN PT_LONG lSlotNr,
    IN PT_BOOL boReturnPayload,
    OUT PT_BIR **ppStoredTemplate
)

现在我需要在C#中为上面的C函数做包装。

我应该如何编组PT_BIR**结构,以及在返回此函数后如何解组呢?

请帮帮我......

1 个答案:

答案 0 :(得分:1)

您需要手动解组。首先在C#

中声明头结构
[StructLayout(LayoutKind.Sequential)]
public struct PT_BIR_HEADER
{
    public int Length; 
    public byte HeaderVersion; 
    public byte Type; 
    public ushort FormatOwner; 
    public ushort FormatID; 
    public char Quality; 
    public byte Purpose; 
    public uint FactorsMask; 
}

然后为函数声明声明ppStoredTemplate参数,如下所示:

out IntPtr ppStoredTemplate

一旦函数返回并且你有ppStoredTemplate,那么你可以解组它。首先拉出标题:

PT_BIR_HEADER header = (PT_BIR_HEADER)Marshal.PtrToStructure(ppStoredTemplate, 
  typeof(PT_BIR_HEADER));

然后你可以解压缩数据:

byte[] data = new byte[header.Length];
Marshal.Copy(ppStoredTemplate + Marshal.SizeOf(typeof(PT_BIR_HEADER)), data, 0, 
    header.Length);