Hi,
I am relatively new to C# and I am having a hard time implementing one function and was hoping that I could get some help from here.
I am trying to call a function from c/c++ library which takes in an array of struct for one of its inputs. I have read few other topics of similar nature, however I was not able to implement this and was hoping that someone could point out what I am doing wrong. It's a function to control FT232RL usb to serial converter.
FT_STATUS FT_GetDeviceInfo (FT_DEVICE_LIST_INFO_NODE *pDest, LPDWORD lpdwNumDevs)
where
FT_DEVICE_LIST_INFO_NODE (see FT_GetDeviceInfoList )
typedef struct _ft_device_list_info_node {
DWORD Flags;
DWORD Type;
DWORD ID;
DWORD LocId;
char SerialNumber[16];
char Description[64];
FT_HANDLE ftHandle;
} FT_DEVICE_LIST_INFO_NODE;
where DWORD and FT_Handle are simply Uint32 and LPDWORD is a pointer to unsigned long (4bytes)
And this is what I have done in c#
[StructLayout(LayoutKind.Sequential)]
public unsafe struct FT_DEVICE_LIST_INFO_NODE
{
public UInt32 ftFlag;
public UInt32 ftType;
public UInt32 ID;
public UInt32 Locld;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] SerialNumber;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public char[] Description;
public FT_HANDLE ftHandle;
}
Imported the function by,
[DllImport("FTD2XX.dll")]
static extern unsafe FT_STATUS FT_GetDeviceInfoList([MarshalAs(UnmanagedType.LPArray)] ref FT_DEVICE_LIST_INFO_NODE[] pdest, ref UInt32 IpdwNumDevs);
and am calling the function using,
FT_DEVICE_LIST_INFO_NODE[] ftNodes = new FT_DEVICE_LIST_INFO_NODE[ftnumdevs];
ftStatus = FT_GetDeviceInfoList(ref ftNodes, ref ftnumdevs);
Where ftnumdevs is the number of devices that are connected, obtained from another function which I have checked and verified it as working. THere are 20+ additional functions in this FTD2XX.dll which I have implemented successfully except for two functions which are the one listed above and another function which allows you to program the EEPROM of the chip and one thing common between the functions are that they take an array of struct as an input.
The error I get when I call this function is
"The runtime has encountered a fatal error. The address of the error was at 0x79e95b95, on thread 0x1454. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack."
Can anyone tell me what I doing wrong?
I also tried implementing it using the IntPtr + Marshalling, however to no avail....
Any kind of help or direction will be appreciated,
Thanks in advance,