Hi
I am trying to make a series of calls to an unmarshalled DLL. The header file for the DLL reads as follows:
In my code I have defined the functions as follows:
InitUSB, USBSendCommand and USBReadData appear to work correctly but when I call USBGetCommand I get a "Value is no longer valid" exception when I try to call Marshal.FreeHGl obal(data);
If I ignore that error and continue running the code then the next time I make the call I get the same exception but in the previous line (Marshal.Copy(d ata, returnBytes, 0, len);) Which means I am unable to see the data returned by the function.
Any help would be appreciated as I am pretty new to marshalling in this way.
Thanks
Brett
I am trying to make a series of calls to an unmarshalled DLL. The header file for the DLL reads as follows:
Code:
BOOL WINAPI InitUSB (void); BOOL WINAPI CloseUSB (void); BOOL WINAPI USBReadData(BYTE Endpoint,DWORD BytesToRead,PBYTE DataBuffer); BOOL WINAPI USBSendCommand(BYTE bCmd); BOOL WINAPI USBGetCommand (BYTE bCmd, WORD wLength, PBYTE pData);
In my code I have defined the functions as follows:
Code:
// declare function
[DllImport("mirwsp", CallingConvention= CallingConvention.StdCall)]
private static extern Boolean InitUSB();
[DllImport("mirwsp", CallingConvention= CallingConvention.StdCall)]
private static extern Boolean CloseUSB();
[DllImport("mirwsp", CallingConvention= CallingConvention.StdCall)]
private static extern Boolean USBSendCommand(byte Cmd);
[DllImport("mirwsp", CallingConvention= CallingConvention.StdCall)]
private static extern Boolean USBGetCommand(byte Cmd, int wLen, ref IntPtr pData);
[DllImport("mirwsp", CallingConvention= CallingConvention.StdCall)]
private static extern Boolean USBReadData(byte EPNumber, long BytesToRead, ref IntPtr DataBuffer);
Code:
private byte[] getCommand(int len, byte command)
{
IntPtr data = Marshal.AllocHGlobal(len);
try {
bool bSuccess = USBGetCommand(command,len,ref data);
byte[] returnBytes = new byte[len];
Marshal.Copy(data, returnBytes, 0, len);
Marshal.FreeHGlobal(data);
} catch (Exception) {
}
return returnBytes;
}
Any help would be appreciated as I am pretty new to marshalling in this way.
Thanks
Brett
Comment