使用DLLImport从非托管DLL调用函数时出现System.AccessViolationException

时间:2019-07-18 09:21:36

标签: c# c++ pinvoke dllimport

我正在尝试使用DLLImport(P / Invoke)从C ++ DLL调用一个函数,并且在我调用它时不断收到System.AccessViolationException错误。请注意,我还有其他功能要工作。

DLLImport函数的声明:

[DllImport("DocProc.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern uint getDPpupTrkBaseConfigPath(DPHandle hdl, StringBuilder str, uint strsize);

用法:

StringBuilder sb = new StringBuilder(256);
                getDPpupTrkBaseConfigPath(handle, sb, (uint)sb.Capacity);

DPHandle :(请注意,它可以在其他函数中使用)

public struct DPHandle
        {
            public uint Size;
            public IntPtr UserHandle;
            [MarshalAs(UnmanagedType.LPStr)] public string DeviceName;
            public uint DeviceTypeId;
            public uint DeviceState;
            public uint OpenFlags;
            public IntPtr Reserved1;
        };

C ++:

BPS_PROPL getDPpupTrkBaseConfigPath(DPHandle hdl, char *str, unsigned long strsize);

(注意BPS_PROPL =无符号长)

DPHandle:

struct DocProcHandle {
    unsigned long Size;//sizeof(DocProcHandle)
    void* UserHandle;
    const char* DeviceName;
    unsigned long DeviceTypeId;
    unsigned long DeviceState;
    unsigned long OpenFlags;
    void* Reserved1;
};
typedef struct DocProcHandle *DPHandle;

同样,当我尝试调用出现异常的函数时。我尝试查看其他答案,但不知道怎么了?

1 个答案:

答案 0 :(得分:0)

在C ++代码中,您具有:

typedef struct DocProcHandle *DPHandle;

这意味着DPHandle是指向该结构的指针。但是在您的C#代码中,您可以按值传递struct。

最简单的实现方法是更改​​pinvoke代码的第一个参数的声明

DPHandle hdl

[In] ref DPHandle hdl