C#调用非托管dll运行时随机报System.AccessViolationException
我写的C#程序有几个接口会频繁调用vc写的非托管dll,这个动态库之前就在用应该没什么大问题
而且程序在运行时也比较正常,但是当我在运行一段时间后,发现程序卡死了(系统呈现死机状态,屏幕保护时按键无法激活显示器),在我写demo测试接口时发现测试程序运行一段时间后程序报错误,错误信息如下:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Common.API.CLIENTStart.Invoke(CHANNELR& _pCHANNEL)
at Common.Monomer.Channel.Connect(IntPtr _hWnd)
at test_Cruse.Connect()
at test_Cruse.tmrCurse_Tick(Object sender, EventArgs e)
at System.Windows.Forms.Timer.OnTick(EventArgs e)
at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
我最初的考虑此问题的可能引发的原因是,系统用调用非托管dll时所传入的结构体中有以string声明的成员,在转入vcdll时需要转换,而且整个结构体在传输时不会被锁定,在调用dll接口时此结构体的内存发生了移动,所以我把string换成了定长的byte[] 但是demo依然会引发System.AccessViolationException异常,不知道有没有人遇到过!
最奇怪的是可能调用此接口50次都不会发生问题,也可能20-30次就会发生此异常,但是一开始运行程序的时候是没问题的。