Roman Gin February 2016

C# P/Invoke 2 dimensional array

I am trying to call a C function from C# code:

typedef char IPTriggerNameType[256];
typedef unsigned long COMM_HANDLE;
typedef BYTE GUID_TYPE[16];
typedef long LONGINT;

typedef struct  {
    GUID_TYPE           Guid;   
    IPTriggerNameType   Name; 
}IPCAM_GENERIC_EVENT_ID;

typedef struct  {
    IPCAM_GENERIC_EVENT_ID      EventId;   
    LONGINT                     RelatedTriggerId;
    LONGINT                     ObsoleteEvent;
}IPCAM_GENERIC_EVENT_INFO;

typedef struct
{
    LONGINT                     NumOfEvents;
    IPCAM_GENERIC_EVENT_INFO    *GenericEventsList;
}VID_CHANNEL_GENERIC_EVENTS_STRUCT;


int __stdcall GetGenericEvents( 
/*  Inputs: */
    COMM_HANDLE                         Handle,                         
    LONGINT                             MaxNumOfChannelsInTable,
    LONGINT                             MaxNumOfEventsPerChannel,

/*  Outputs: */    
    LONGINT                             *NumOfChannels,
    VID_CHANNEL_GENERIC_EVENTS_STRUCT   *ChannelsEventsTable);

and the C# equivalent is as follows:

[StructLayout(LayoutKind.Sequential)]
    public struct IPCAM_GENERIC_EVENT_ID
    {
        [MarshalAs(UnmanagedType.LPArray, SizeConst = 16)]
        public byte[] Guid;

        [MarshalAs(UnmanagedType.LPArray, SizeConst = 256)]
        public char[] Name;
    };

    [StructLayout(LayoutKind.Sequential)]
    public struct IPCAM_GENERIC_EVENT_INFO
    {
        public IPCAM_GENERIC_EVENT_ID EventId;
        public int RelatedTriggerId;
        public int ObsoleteEvent;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct VID_CHANNEL_GENERIC_EVENTS_STRUCT
    {
        public int NumOfEvents;

        [MarshalAs(UnmanagedType.LPArray, SizeConst = 100)]
        public IPCAM_GENERIC_EVENT_INFO[] GenericEventsList;
    }

    [DllImport(dllName)]
public static extern int GetGenericEvents(
    /*  Inputs: */
    int Handle,
    int MaxNumOfChannelsInTable,
    int MaxNumOfEve        

Answers


Cecilio Pardo February 2016

The field:

VID_CHANNEL_GENERIC_EVENTS_STRUCT.GenericEventsList

is a pointer, declared as:

IPCAM_GENERIC_EVENT_INFO *GenericEventsList

But you are declaring it as an array, included in the struct:

[MarshalAs(UnmanagedType.LPArray, SizeConst = 100)]
public IPCAM_GENERIC_EVENT_INFO[] GenericEventsList;

You may try to use an IntPtr and Marshal.AllocHGlobal. Check this out: How use pinvoke for C struct array pointer to C#

Post Status

Asked in February 2016
Viewed 2,047 times
Voted 10
Answered 1 times

Search




Leave an answer