这是我的第一篇 stackoverflow 帖子。这几天我一直在纠结这个问题。我尝试将作为 C Dll 的 usbi2cio.dll 导入基于 C# 的项目。我浏览了网站中的大多数类似帖子,但我仍然无法解决我的问题,因为我的情况可能略有不同。
所以这里是作为参数的 API 和相关结构的原始定义:
LONG _stdcall DAPI_ReadI2c(HANDLE hDevInstance, I2C_TRANS * TransI2C);
typedef struct _I2C_TRANS {
BYTE byTransType;
BYTE bySlvDevAddr;
WORD wMemoryAddr;
WORD wCount;
BYTE Data[256];
}I2C_TRANS, *PI2C_TRANS;
//In my C# code, I did the translation like this:
[StructLayoutAttribute(LayoutKind.Sequential), Serializable]
public struct I2C_TRANS
{
public byte byTransType;
public byte bySlvDevAddr;
public ushort wMemoryAddr;
public ushort wCount;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 256, ArraySubType = UnmanagedType.I1)]
public byte[] Data;
public I2C_TRANS(int size)
{
Data = new byte[size];
this.byTransType = 0x00;
this.bySlvDevAddr = 0x00;
this.wMemoryAddr = 0;
this.wCount = 0;
}
};
public I2C_TRANS TransI2C = new I2C_TRANS(256);
public IntPtr[] hDevice = new IntPtr[DAPI_MAX_DEVICES];
...
TransI2C.byTransType = byTransType;
TransI2C.bySlvDevAddr = bySlvDevAddr;
TransI2C.wMemoryAddr = wMemoryAddr;
TransI2C.wCount = wCount;// no larger than 64
...
if((hDevice[0] = DAPI_OpenDeviceInstance(devName, 0)) != INVALID_HANDLE_VALUE)
//the returned lReadCnt should be equal to wCount.
Public int lReadCnt = DAPI_ReadI2c(hDevice[0], ref TransI2C);
由于某种原因,读取的 I2C 事务中的 struct 无法很好地传递,因此该函数返回 0 值而没有错误(我期望与 wCount 的值相同)。对于其他一些类似的 API 和结构,它运行良好。那么这个问题的原因可能是什么?
//Here is the P/Invoke declaration:
[DllImportAttribute("UsbI2cIo.dll", EntryPoint = "DAPI_ReadI2c", CallingConvention = CallingConvention.StdCall)]
public static extern int DAPI_ReadI2c(IntPtr hDevInstance, ref I2C_TRANS TransI2C);