使用正确的数据类型在CSharp中加载C ++ dll

时间:2018-01-17 08:17:39

标签: c# c++ visual-studio dll

需要从CSharp中的DLL加载这个C ++方法,我想知道我必须使用哪些数据类型?

WORD FunA (BYTE Num, BYTE *pFrameTX, DWORD nbbitTX, BYTE
*pFrameRX, DWORD *pnbbitRX)

我的第一个方法是:

[DllImport("Example.Dll")]
public static extern UInt16 FunA(byte Num, Byte[] pFrameTX, UInt32 nbbitTX, ref Byte[] pFrameRX, ref UInt32 pnbbitRX);

Byte[] toSend = new Byte[1], toReceive = new Byte[1024];
toSend[0] = 0x26;
UInt32 numberOfBitsReceived = 0;

FunA(Convert.ToByte(1), toSend, 0, ref toReceive, ref numberOfBitsReceived);

这里有什么问题?有人可以帮我找到正确的数据类型和调用用法吗?!

谢谢!

2 个答案:

答案 0 :(得分:0)

猜猜你错过了pFrameTX前面的ref修饰符。

[DllImport("Example.Dll")]
public static extern UInt16 FunA(byte Num, ref Byte[] pFrameTX, UInt32 
nbbitTX, ref Byte[] pFrameRX, ref UInt32 pnbbitRX);

答案 1 :(得分:0)

[DllImport("Example.Dll")]
public static extern UInt16 FunA(byte Num, IntPtr pFrameTX, UInt32 
nbbitTX, IntPtr pFrameRX, ref UInt32 pnbbitRX);

// ...    

Byte[] toSend = new Byte[1], toReceive = new Byte[1024];
toSend[0] = 0x26;
UInt32 numberOfBitsReceived = 0;

// reserve unmanaged memory for IntPtr
IntPtr toSendPtr = Marshal.AllocHGlobal(Marshal.SizeOf(toSend[0])*toSend.Length),
    toReceivePtr = Marshal.AllocHGlobal(Marshal.SizeOf(toReceive[0])*toReceive.Length);

// copy send buffer to Unmanaged memory
Marshal.Copy(toSend, 0, toSendPtr, toSend.Length);

// call C++ DLL method
FunA(Convert.ToByte(1), toSendPtr, 0, toReceivePtr, ref numberOfBitsReceived);

// copy receive buffer from Unmanaged to managed memory
Marshal.Copy(toReceivePtr, toReceive, 0, numberOfBitsReveived/8);

// free memory
Marshal.FreeHGlobal(toSendPtr);
Marshal.FreeHGlobal(toReceivePtr);