PInvoke期间发生访问冲突

本文关键字:访问冲突 PInvoke | 更新日期: 2023-09-27 18:23:43

我有这个dll调用:

 [DllImport("FreqCntPcIntf.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern Intf_ErrorType FreqCntIntf_Init(
        ref byte InstNo, 
        string InstName, 
        string PortServerName, 
        ulong UartComPort, 
        ulong MaxBlockTime);
enum Intf_ErrorType
{
    ...
}

C++声明是这样的:

FREQCNTINTF_API Intf_ErrorType STDCALL FreqCntIntf_Init(InstanceNoType* InstNo, const char* InstName, const char* PortServerName, rsuint32 UartComPort, rsuint32 MaxBlockTime); 

其中:

typedef enum 
{
   ....
}  RSENUM8(Intf_ErrorType);
#define FREQCNTINTF_API __declspec(dllexport)
typedef rsuint8 InstanceNoType;
typedef unsigned char rsuint8;
#define RSENUM32(EnumName)  Enum_##EnumName; typedef rsuint32 EnumName

我在通话中收到AccessViolation。我应该在哪里查找bug?

PInvoke期间发生访问冲突

rsuint32应该表示为uint,它是4字节宽,而不是ulong,它在C#中是8字节长。此外,您可能希望通过指定CharSet来确保您的字符串是编组的proplery,如下所示:

[DllImport("FreqCntPcIntf.dll", CallingConvention = CallingConvention.StdCall, CharSet=CharSet.Ansi)]