繁体   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