Note that there are some explanatory texts on larger screens.

plurals
  1. POCannot p/invoke C method from C# due to marshalling issues
    primarykey
    data
    text
    <p>I'm trying to invoke the <code>I2CTransfer</code> function below, and immediately getting a <code>System.NotSupportedException</code>. I suspect my marshalling is wrong, but cannot work out the problem.</p> <hr> <p>Here are the C structures:</p> <pre><code>BOOL I2CTransfer(HANDLE hDev, PI2C_TRANSFER_BLOCK pI2CTransferBlock); typedef struct { I2C_PACKET *pI2CPackets; INT32 iNumPackets; } I2C_TRANSFER_BLOCK, *PI2C_TRANSFER_BLOCK; typedef struct { BYTE byAddr; BYTE byRW; PBYTE pbyBuf; WORD wLen; LPINT lpiResult; } I2C_PACKET, *PI2C_PACKET; </code></pre> <hr> <p>And here are the c# structures I'm attempting: </p> <pre><code>[DllImport("i2csdk.dll", EntryPoint = "I2CTransfer")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool I2CTransfer(IntPtr hI2C,ref I2C_TRANSFER_BLOCK pI2CTransferBlock); [StructLayout(LayoutKind.Sequential)] public struct I2C_TRANSFER_BLOCK { public I2C_PACKET[] pI2CPackets; public int iNumPackets; } [StructLayout(LayoutKind.Sequential)] public struct I2C_PACKET { public byte byAddr; public byte byRW; public byte[] pbyBuf; public UInt16 wLen; public IntPtr lpiResult; } </code></pre> <hr> <p>Calling code:</p> <pre><code>I2C_TRANSFER_BLOCK i2CTransferBlock = new I2C_TRANSFER_BLOCK(); I2C_PACKET packet = new I2C_PACKET(); int result; IntPtr resultPtr = IntPtr.Zero; //Populating data... byte[] pBuf = new byte[1 + pbData.Length]; pBuf[0] = (byte) ((regStart &amp; 0x7F) &lt;&lt; 1); Array.Copy(pbData, 0, pBuf, 1, pbData.Length); // Fill packet for register write packet.pbyBuf = pBuf; packet.wLen = (ushort) pBuf.Length; packet.byRW = NativeConstants.I2C_RW_WRITE; packet.byAddr = address; packet.lpiResult = resultPtr; // Fill transfer block i2CTransferBlock.pI2CPackets = new I2C_PACKET[] {packet}; i2CTransferBlock.iNumPackets = 1; // NotSupportedException here bool brc = I2CTransfer(port, ref i2CTransferBlock); </code></pre> <hr> <p>The arrays are initialized in C# before calling the method. </p> <p>I've tried adding <code>[MarshalAs(UnmanagedType.LPArray)]</code></p> <p>to the arrays (pI2cPackets, and pbyBuf) to no avail. </p> <p>This is on Windows CE - compact framework, .NET 3.5.</p> <p>Is there something obviously wrong with the above translation?</p> <p>Many thanks in advance. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload