簡體   English   中英

如何防止非托管dll調用訪問沖突?

[英]How to prevent access violation on unmanaged dll call?

我們繼承了一種傳統的系統,用於讀取和從瞄准槍讀取。 該系統最初是在帶有.Net 1.1(VS2003?)的XP上構建的。 在VS2008上使用.net 3.5重新編譯它時,我們在調用dll時遇到訪問沖突(未觸及dll)。 原始程序(使用基本相同的代碼)在我們的生產機器上正常運行。

崩潰:

[System.AccessViolationException]
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

碼:

[DllImport("tinydb.dll",CallingConvention=CallingConvention.Cdecl)]
static extern Int16 db_fillnew(Int16 recno,IntPtr buffer,Int16 dbn);
     :
     :
    IntPtr buffer = Marshal.AllocHGlobal(1024); 
     :
     :
foreach (Round round in roundList)
{
    RoundRec roundRec=new RoundRec();
    roundRec.Book=Int16.Parse(round.Reference);
    roundRec.NLegend=round.Name;
    Marshal.StructureToPtr(roundRec,buffer,true);
    status = db_fillnew(ROUND_REC,buffer,0); // <=CRASHES HERE

它總是在循環周圍第二次崩潰。

這是記錄結構:

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
struct RoundRec
{
    public Int16 Book;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)]
    public string NLegend; public string LastReadRefNo;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)]
    public string LastNoAccessRefNo;
}

嘗試為每條記錄分配和釋放內存:

foreach (Round round in roundList)
{
  RoundRec roundRec = new RoundRec();
  roundRec.Book=Int16.Parse(round.Reference);
  roundRec.NLegend = round.Name;

  IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(roundRec));

  Marshal.StructureToPtr(roundRec, buffer, true);
  status = db_fillnew(ROUND_REC, buffer, 0);

  Marshal.FreeHGlobal(buffer);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM