将C dll函数导入C#

时间:2013-04-08 18:39:50

标签: c# dll i2c

这是我的第一篇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事务中的结构不能很好地通过,因此,该函数返回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); 

1 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,我通过编写自己的名为Bridge的C库来修复它,它将处理复杂的C API,但是可以轻松地接触可以与C#接口的简单方法。

例如,在下面的方法中,我可以将一个字节数组传递给我的C代码。 从C#的角度来看,我只处理byte,int16或int32或字节数组。

[DllImport(DLL)]
private static extern System.Int32 __SPI_Helper_Write(IntPtr lpBuffer, System.Int32 len);