none
C#调用C++ DLL的难题 RRS feed

  • 问题

  • 请教大家一个问题,现在有个C++ PCIDLL.dll文件,在C#中调用 dll,出现错误如下:System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    请问C#代码哪里有误,烦请高手指点,谢谢!

    C++ Code:

    结构体:
    typedef struct _DEV_CTRL_PARAM
    {
    int ScanType;
    int SelChannel[12];
    int mParamType;
    int *mEtalonPeakNum;
    float *p_EtalonPeakVal;
    }DEV_CTRL_PARAM,*PDEV_CTRL_PARAM;

    extern BOOL _stdcall Pci_InitDevice(int mDev,PDEV_CTRL_PARAM pParam);

    调用:
    int mEtalonPeakNum = 0;
    float EtalonPeakVal[400];
    DEV_CTRL_PARAM mParam;
    int temptype[7] ={6,5,4,3,2,1,0};
    mParam.ScanType=3;
    mParam.mParamType = 0;

    mParam.mEtalonPeakNum = &mEtalonPeakNum;
    mParam.p_EtalonPeakVal = EtalonPeakVal;

    mParam.SelChannel[0] = 1;
    mParam.SelChannel[1] = 1;
    mParam.SelChannel[2] = 1;
    mParam.SelChannel[3] = 1;
    mParam.SelChannel[4] = 1;
    mParam.SelChannel[5] = 1;
    mParam.SelChannel[6] = 1;
    mParam.SelChannel[7] = 1;
    mParam.SelChannel[8] = 1;
    mParam.SelChannel[9] = 1;
    mParam.SelChannel[10] = 0;
    mParam.SelChannel[11] = 0;

    Pci_InitDevice(0,&mParam);

    ----------------------------------------------------------------------------------

    C# Code:

    结构体:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct DEV_CTRL_PARAM
    {
    [MarshalAs(UnmanagedType.I4)]
    public int ScanType;

    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I4, SizeConst = 12)]
    public int[] SelChannel;

    [MarshalAs(UnmanagedType.I4)]
    public int mParamType;

    [MarshalAs(UnmanagedType.I4)]
    public int mEtalonPeakNum;

    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.R4, SizeConst = 400)]
    public Single[] p_EtalonPeakVal;
    }


    [DllImport("PCIDLL.dll")]
    public static extern bool Pci_InitDevice(int mDev, ref DEV_CTRL_PARAM pParam);


    调用:
    DEV_CTRL_PARAM mParam;
    mParam.SelChannel = new int[12];

    int mEtalonPeakNum = 0;
    float[] EtalonPeakVal = new float[400];
    int[] temptype = new int[7] { 6, 5, 4, 3, 2, 1, 0 };
    mParam.ScanType = 3;
    mParam.mParamType = 0;

    mParam.mEtalonPeakNum = mEtalonPeakNum;
    mParam.p_EtalonPeakVal = EtalonPeakVal;

    mParam.SelChannel[0] = 1;
    mParam.SelChannel[1] = 1;
    mParam.SelChannel[2] = 1;
    mParam.SelChannel[3] = 1;
    mParam.SelChannel[4] = 1;
    mParam.SelChannel[5] = 1;
    mParam.SelChannel[6] = 1;
    mParam.SelChannel[7] = 1;
    mParam.SelChannel[8] = 1;
    mParam.SelChannel[9] = 1;
    mParam.SelChannel[10] = 0;
    mParam.SelChannel[11] = 0;

    Pci_InitDevice(0, ref mParam);
    2012年1月10日 7:44

答案

全部回复