Hi
I'm making a call to an unmanaged C++ library in order to retrieve data from a device, I have tried numerous different methods but can't seem to get the call to work.
I'm pretty to new to making calls to unmanaged code.
Here's what I've got:
Code:
[DllImport("foo", EntryPoint = "USBReadData", CallingConvention= CallingConvention.StdCall, SetLastError = true)]
public static extern Boolean USBReadData(byte EPNumber, long BytesToRead, MY_STRUCT DataBuffer);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct MY_STRUCT{
[MarshalAs(UnmanagedType.I2)]
public Int16 Value1;
[MarshalAs(UnmanagedType.I2)]
public Int16 Value2;
[MarshalAs(UnmanagedType.I2)]
public Int16 Value3;
}
internal void readDataFromDevice(long length){
MY_STRUCT results = new MY_STRUCT();
if (USBReadData(1, length, results) == true) {
//Great - its working!!
;
}else{
System.Diagnostics.Debug.Print(Marshal.GetLastWin32Error().ToString());
throw new Exception("Could not read data.");
}
}
Using this I get a Win32 998 error.
BTW the length of the structure is known in advance
I also tried to do it using a pointer like this:
Code:
[DllImport("foo", EntryPoint = "USBGetCommand", CallingConvention= CallingConvention.StdCall, SetLastError = true)]
public static extern Boolean USBGetCommandWithBuffer(byte Cmd, int wLen, IntPtr pData);
internal void readDataFromDevice(long length){
byte[] results = new byte[6];
IntPtr ptr = Marshal.AllocHGlobal(results.length);
Marshal.Copy(results,0, ptr, results.Length);
if (USBReadData(1, length, ptr) == true) {
Marshal.FreeHGlobal(ptr);
}else{
throw new Exception("Could not read data.");
}
}
When I run this one it freezes at if (USBReadData(1, length, ptr) == true) and occasionally gives me an "Out of memory" error.
Finally I've tried just passing an array like so:
Code:
[DllImport("foo", EntryPoint = "USBReadData", CallingConvention= CallingConvention.StdCall, SetLastError = true)]
public static extern Boolean USBReadData(byte EPNumber, long BytesToRead, short[] DataBuffer);
internal void readDataFromDevice(long length){
short[] results = new short[57];
if (USBReadData(1, length, results) == true) {
System.Diagnostics.Debug.Print("We're here!");
}else{
System.Diagnostics.Debug.Print(Marshal.GetLastWin32Error().ToString());
throw new Exception("Could not read test results.");
}
}
The first time I ran this I got "We're here!" as output but every subsequent time I have run it I get the same Win32 998 error.
Any help would be very much appreciated.
Thanks