[英]Calling non-managed DLL
试图从C#应用程序调用DLL函数几天让我发疯。
这是DLL调用的定义:
phStatus_t phbalReg_Rd70xUsbWin_Init
( phbalReg_Rd70xUsbWin_DataParams_t * pDataParams,
uint16_t wSizeOfDataParams )
这是phbalReg_Rd70xUsbWin_DataParams_t
的定义:
这是我用于调用DLL的C#代码:
public static data_params parameters;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct data_params
{
internal ushort wId; //Layer ID for this BAL component, NEVER MODIFY!
internal byte ucTxSeq; //Sequence counter for packets.
[MarshalAs(UnmanagedType.LPStr)]
String pDeviceName;
internal IntPtr pDeviceHandle; //Handle to the USB device.
internal IntPtr pPipeOut; //Handle to Usb Out-pipe.
internal IntPtr pPipeIn; //Handle to Usb In-pipe.
internal ushort wTimeoutWrMs; //TO value for Usb Write pipe transfer.
internal ushort wTimeoutRdMs; //TO value for Usb Read pipe transfer.
}
[DllImport("NxpRdlib.dll", EntryPoint = "phbalReg_Rd70xUsbWin_Init")]
public static extern uint phbalReg_Rd70xUsbWin_Init(ref data_params data_parameters,
public static unsafe uint connectToPegoda()
{
parameters = new data_params();
parameters.wId = 0x05;
parameters.ucTxSeq = 0;
parameters.pDeviceHandle = IntPtr.Zero;
parameters.pPipeOut = IntPtr.Zero;
parameters.pPipeIn = IntPtr.Zero;
parameters.wTimeoutWrMs = 0xFFFF;
parameters.wTimeoutRdMs = 0xFFFF;
return phbalReg_Rd70xUsbWin_Init(ref parameters, (uint)Marshal.SizeOf(parameters));
}
问题是我收到PInvokeStackImbalance
异常。
我试图用不同的东西来改变参数的类型,但是却没有实现这项工作。 我确定我对类型做错了,但是找不到。 有人能帮我吗?
最常见的解释是调用约定不匹配。 如所写,非托管函数声明使用cdecl。 您未在p / invoke中指定调用约定,因此使用了默认的stdcall。
要解决此问题,请在p / invoke中指定cdecl:
[DllImport("NxpRdlib.dll", CallingConvention = CallingConvention.Cdecl)]
您还只指定了p / invoke声明的一部分。 您错过了第二个参数。 完整的声明应为:
[DllImport("NxpRdlib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern uint phbalReg_Rd70xUsbWin_Init(
ref data_params data_parameters,
ushort wSizeOfDataParams
);
另一个未知的是phStatus_t
。 您已经将其转换为uint
,这是一个无符号的32位整数。 我们只能相信您的翻译是正确的。
更新 :从您的评论到问题, phStatus_t
应该翻译为ushort
。 因此,最后,我们有:
[DllImport("NxpRdlib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern ushort phbalReg_Rd70xUsbWin_Init(
ref data_params data_parameters,
ushort wSizeOfDataParams
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.