最近一直被C# 调用native code时的内存错误,各种错误所困扰。而且在.net 4.0中非托管代码的异常不能被托管代码抓获,导致程序直接crash。
最终找到了.net 的方法。MSDN有关于expection 的详细解释。
1. 在.net 3.5中是可以抓取AccessViolationException这个C崩溃的异常的,因此可以尝试使用这个.net 3.5重新编译
2.在.net 4,4.5中可以尝试在app.config 文件中加上如下的配置,
<configuration>
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true"/>
</runtime>
<configuration>
3.为函数标记[HandleProcessCorruptedStateExceptions]
// This program runs as part of an automated test system so you need // to prevent the normal Unhandled Exception behavior (Watson dialog). // Instead, print out any exceptions and exit with an error code. [HandleProcessCorruptedStateExceptions] [SecurityCritical] public static int Main() { try { // Catch any exceptions leaking out of the program CallMainProgramLoop(); } catch (Exception e) // We could be catching anything here { // The exception we caught could have been a program error // or something much more serious. Regardless, we know that // something is not right. We‘ll just output the exception // and exit with an error. We won‘t try to do any work when // the program or process is in an unknown state! System.Console.WriteLine(e.Message); return 1; } return 0; }
但是我使用第二种方法,仍然未解决问题,留待解决。
关于C# 调用 C dll时,抓获C的异常,布布扣,bubuko.com
原文:http://www.cnblogs.com/stupidhod/p/3791022.html