私はいくつかの画像処理コードを書いており、C# を使用して低レベルのピクセル操作を行っています。時々、accessViolationException が発生します。
この典型的な問題にはいくつかのアプローチがあり、アクセス違反の例外が発生しないようにコードを堅牢に記述する必要があると考える人もいます。私が試した限りでは、アプリケーションは問題なく動作していますが、何かが発生した場合にトライ キャッチを追加したいと考えています。場合によっては、アプリケーションがあまりにも醜い方法で失敗することはありません。
これまでのところ、テストするためにいくつかのサンプルコードを入れました
unsafe
{
byte* imageIn = (byte*)img.ImageData.ToPointer();
int inWidthStep = img.WidthStep;
int height = img.Height;
int width = img.Width;
imageIn[height * inWidthStep + width * 1000] = 100; // make it go wrong
}
このステートメントの周りに try catch を配置しても、例外が発生します。安全でないブロックで生成された例外をキャッチする方法はありますか?
編集: 以下に記載されているように、この属性を関数に追加し、「using System.Runtime.ExceptionServices」を追加してチェックを明示的に有効にしない限り、このタイプの例外は処理されなくなりました。
[HandleProcessCorruptedStateExceptions]
public void makeItCrash(IplImage img)
{
try
{
unsafe
{
byte* imageIn = (byte*)img.ImageData.ToPointer();
int inWidthStep = img.WidthStep;
int height = img.Height;
int width = img.Width;
imageIn[height * inWidthStep + width * 1000] = 100; // to make it crash
}
}
catch(AccessViolationException e)
{
// log the problem and get out
}
}