2

多数のDBaseIVファイルのメモフィールドからC++構造をC#(.Net 4)に読み取り、それらをMSSQL 2008に挿入しようとすると、問題が発生します。データはDBaseファイルから正常に抽出されていますが、次のエラーがランダムに発生するため、安全でない呼び出しの管理で何か問題が発生している可能性があります。

FatalExecutionEngineError was detected
Message: The runtime has encountered a fatal error. The address of the error was
at 0x791fa62c, on thread 0x16c0. The error code is 0xc0000005. This error may be
a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common
sources of this bug include user marshaling errors for COM-interop or PInvoke, 
which may corrupt the stack. 

以下は、データを読み取るために使用するコードです。このコードは正常に完了し、ファイルから取得したデータは正しいです。このエラーは、この関数が呼び出されてから数分後に、オブジェクトがnhibernateを使用してデータベースに挿入されているときに発生します(問題にあまり関係ないと思ったため、省略しました)。

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Event
{        
    public int      Number;
    public int      Month;
    public int      Day;
    public int      Year;
    public int      Hour;
    public int      Minute;
    public int      Second;
    public UInt32   UPCTime;
    public int      BlobSize;
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = DataLengths.MAX_EVENT_TITLE_LENGTH)]
    public string   Title;
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = DataLengths.MAX_TRIGGER_LENGTH)]
    public string Trigger;
 }

public struct Trigger
{
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 1)]
    public string Control;
    public int Index;
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 1)]
    public string Mode;
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 1)]
    public string RecordFreq;
    public int Pre;
    public int Post;
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 1)]
    public string Source;
    public int Delay;
    public int EventUserNotify;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)]
    public int[] Spare;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = DataLengths.MAX_EVENT_SENSORS)]
    public int[] Sensors;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Value
{
    public Trigger Trigger;
    public string[] SensorLabels;
    public Point[] Point;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Point
{
    public Single Value;
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 1)]
    public string State;
}

//The dbf is from the java xBasej library that I compiled into a dll using IKVM.net
public Dictionary<Event, Value> Read(DBF dbf)
{     
Dictionary<Event, Value> eventData = new Dictionary<Event, Value>();

try
{
    for (int i = 1; i <= dbf.getRecordCount(); i++)
    {
         dbf.gotoRecord(i);
         MemoField memofield = (MemoField)dbf.getField("MemoField");

         // Perform the conversion from one encoding to the other.
         byte[] blob = memofield.getBytes();

         if (blob.Length == 0)
         {
             continue;
         }

         MemoryStream memoryStream = null;
         BinaryReader binaryReader = null;
         GCHandle eventHandle = new GCHandle();
         GCHandle triggerHandle = new GCHandle();
         GCHandle sensorLabelHandle = new GCHandle();
         GCHandle pointHandle = new GCHandle();

         try
         {
             memoryStream = new MemoryStream(blob);
             binaryReader = new BinaryReader(memoryStream);

             //The data was orignally C++ structures so we read the bytes back into C# equivalent
             //structures.
             int eventDataSize = Marshal.SizeOf(typeof(Event));

             eventHandle = GCHandle.Alloc(binaryReader.ReadBytes(eventDataSize), GCHandleType.Pinned);
             Event @event = (Event)Marshal.PtrToStructure(eventHandle.AddrOfPinnedObject(), typeof(Event));

             //Read the event trigger data
             int triggerDataSize = Marshal.SizeOf(typeof(Trigger));
             triggerHandle = GCHandle.Alloc(binaryReader.ReadBytes(triggerDataSize), GCHandleType.Pinned);
             Trigger trigger = (Trigger)Marshal.PtrToStructure(triggerHandle.AddrOfPinnedObject(), typeof(Trigger));

             Value value = new Value();
             value.Trigger = trigger;

             triggerHandle.Free();

             //Read all the sensor labels
             List<string> sensorLableList = new List<string>();
             for (int sensorIndex = 0; sensorIndex < DataLengths.MAX_EVENT_SENSORS; sensorIndex++)
             {
                   int sensorLableDataSize = DataLengths.MAX_LABEL_LENGTH;
                   sensorLabelHandle = GCHandle.Alloc(binaryReader.ReadBytes(sensorLableDataSize), GCHandleType.Pinned);
                  string label = Marshal.PtrToStringAnsi(sensorLabelHandle.AddrOfPinnedObject(), sensorLableDataSize).Trim();
                   sensorLableList.Add(label);

                   sensorLabelHandle.Free();
             }
             value.SensorLabels = sensorLableList.ToArray();
             //Read all the recorded sensor data
             List<Point> pointList = new List<Point>();
             for (int pointIndex = 0; pointIndex < DataLengths.MAX_EVENT_SENSORS; pointIndex++)
             {
                  int pointDataSize = Marshal.SizeOf(typeof(Point));

                  pointHandle = GCHandle.Alloc(binaryReader.ReadBytes(pointDataSize), GCHandleType.Pinned);
                  Point point = (Point)Marshal.PtrToStructure(pointHandle.AddrOfPinnedObject(), typeof(Point));
                  pointList.Add(point);

                  pointHandle.Free();
             }

             value.Point = pointList.ToArray();

             eventData.Add(@event, value);
             eventHandle.Free();
        }
        finally
        {
             //Free all the resources used to get the data
             if (memoryStream != null) { memoryStream.Close(); }
             if (binaryReader != null) { binaryReader.Close(); }
             if (eventHandle.IsAllocated) { eventHandle.Free(); }
             if (triggerHandle.IsAllocated) { triggerHandle.Free(); }
             if (sensorLabelHandle.IsAllocated) { sensorLabelHandle.Free(); }
             if (pointHandle.IsAllocated) { pointHandle.Free(); }

             GC.Collect();
         }
    }

}
finally
{
     if (dbf != null)
     {
        dbf.close();
     }
}                

return eventData;
}
4

2 に答える 2

4

興味深い障害モードです。これは発生しないはずです。通常、ガベージ コレクション ヒープが破棄されるため、FEEE が発生します。これは通常、ピンボークされたネイティブ関数が不適切な動作をし、バッファのオーバーフローなどを行うことで簡単に説明できます。ただし、ここではピンボークはありません。

ただし、この事故の優れた候補があります。

[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 1)]
public string Control;

このマーシャリングは、ゼロで終わる文字配列である C 文字列をマーシャリングするように設計されています。SizeConst = 1 は、文字ではなくゼロ ターミネータの余地を残すだけで、設計上正しく機能しません。その上、.dbf ファイルにはゼロで終了する文字列は含まれず、フィールド宣言に従って固定幅になります。

マーシャラーがこれを間違えたためにアクセス違反が実際に引き起こされたのかどうかは未解決の問題ですが、ゼロターミネーターを見つけようとすると簡単に爆破される可能性があります。1つが見つからず、マップされていないメモリページに失敗します。

とにかく、あなたはそれを間違っています。構造体宣言では文字列の代わりに char[] を使用し、[MarshalAs] 属性では ByValArray を使用する必要があります。ところで、かなり面倒なコーディング。

于 2011-03-25T21:48:15.253 に答える
0

Trigger 構造内で、適切なパッキングがあると確信していますか? Index メンバーはオフセット 4 にあるように見えますが、オフセット 1 にあることを意図していたのでしょうか? プリとポストも同様です。

また、コントロールのサイズはどのくらいですか? 文字列の場合、通常、アンマネージ文字列は null で終了します。長さ 1 を指定することで、1 文字であることを示します。その場合は、string の代わりに char を使用してみませんか?

エラー 0xc0000005 はアクセス違反です。

デバッガーで実行し、アンマネージ コードのデバッグを有効にしてみましたか? 次に、.NET フレームワーク コード内で発生している可能性があるため、アクセス違反がスローされたときにすぐにキャッチされるように設定できます。次に、メモリを見て、それが何をしているのかを知ることができます。

于 2011-03-25T21:11:27.200 に答える