SaddamBinSyed
SaddamBinSyed

Reputation: 603

How to marshal this nested, variable-length C structure in C#

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

And my C function is:

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

Now I need to do the wrapper for the above C function in C#.

How should I marshal the PT_BIR** structure and how should I unmarshal it after return of this function?

Please help me ...

Upvotes: 1

Views: 246

Answers (1)

David Heffernan
David Heffernan

Reputation: 612983

You are going to need to unmarshal this manually. First of all declare the header struct in 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; 
}

Then for the function declaration declare the ppStoredTemplate parameter like this:

out IntPtr ppStoredTemplate

Once the function returns and you have ppStoredTemplate, then you can unmarshal it. First of all pull out the header:

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

And then you can unpack the data:

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

Upvotes: 1

Related Questions