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

Load C++ dll in CSharp with correct datatypes

本文关键字:数据类型 加载 C++ dll CSharp      更新时间:2023-10-16

需要从 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);

这是怎么回事?有人可以帮助我找到正确的数据类型和调用用法吗?!

谢谢!

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

[DllImport("Example.Dll")]
public static extern UInt16 FunA(byte Num, ref Byte[] pFrameTX, UInt32 
nbbitTX, ref Byte[] pFrameRX, ref UInt32 pnbbitRX);
[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);