Calling unmanaged C++ library (dll) from C# creates an access violation error (0xc0000005)

廉价感情. 提交于 2019-11-30 23:26:16

Your structs are marshalled incorrectly because you didn't declare the arrays quite right. You need to tell the marshaller that they are fixed length arrays.

EDIT

In my original answer I missed the addition error that the bool members were not marshalled correctly. The default marshalling is for the 4 byte Windows BOOL but you need 1 byte C++ bool. The code below now handles that correctly. Sorry for the confusion.

public struct PDWaveSample
{
    [MarshalAs(UnmanagedType.I1)]
    public bool bValid;                             
    public float fPressure;                         
    public float fDistance;                         
    [MarshalAs(UnmanagedType.LPArray, SizeConst=4)]
    public float[] fVel;
    [MarshalAs(UnmanagedType.LPArray, SizeConst=4)]
    public ushort[] nAmp
}

public struct PDWaveBurst {
    [MarshalAs(UnmanagedType.LPArray, SizeConst=4096)]
    public float[] fST;
    public float fWinFloor;
    public float fWinCeil;
    [MarshalAs(UnmanagedType.I1)]
    public bool bUseWindow;
    [MarshalAs(UnmanagedType.I1)]
    public bool bSTOk;
    [MarshalAs(UnmanagedType.I1)]
    public bool bGetRawAST;
    [MarshalAs(UnmanagedType.I1)]
    public bool bValidBurst;
}

Actually, I had to marshall the arrays as ByValArray. Otherwise the running environment had something to complain about:

"A first chance exception of type 'System.TypeLoadException' occurred in CalculationForm.exe

Additional information: Cannot marshal field 'fVel' of type 'PdWaveApi.PDWaveSample': Invalid managed/unmanaged type combination (Arrays fields must be paired with ByValArray or SafeArray)."

So, I changed the struct to this:

public struct PDWaveSample
{
    [MarshalAs(UnmanagedType.I1)]
    public bool bValid;                             
    public float fPressure;                         
    public float fDistance;                         
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
    public float[] fVel;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
    public ushort[] nAmp
}

public struct PDWaveBurst {
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=4096)]
    public float[] fST;
    public float fWinFloor;
    public float fWinCeil;
    [MarshalAs(UnmanagedType.I1)]
    public bool bUseWindow;
    [MarshalAs(UnmanagedType.I1)]
    public bool bSTOk;
    [MarshalAs(UnmanagedType.I1)]
    public bool bGetRawAST;
    [MarshalAs(UnmanagedType.I1)]
    public bool bValidBurst;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!