【问题标题】:AccessViolationException when accessing unmanaged C++ DLL with C#使用 C# 访问非托管 C++ DLL 时出现 AccessViolationException
【发布时间】:2015-11-21 12:23:59
【问题描述】:

我正在尝试从 C# 项目访问非托管 C++ 代码的 Double Dummy Solver dll (http://privat.bahnhof.se/wb758135/bridge/dll.html),但收到以下错误消息:

“System.AccessViolationException”类型的未处理异常 发生在 Dds.Net.dll

附加信息:试图读取或写入受保护的内存。 这通常表明其他内存已损坏。

错误似乎与调用方法有关 Par 接受三个参数

struct ddTableResults *tablep, struct parResults *presp, int 易受攻击

具体来说,与传入第二个参数有关,描述为:

结构parResults 字符 parScore[2][16]; char parContractsString [2][128];

这是我的代码: 我的 c# 结构:

using System.Runtime.InteropServices;

namespace Dds.Net.Integration
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct ParResults
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst =32)]
        public char[,] parScore;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
        public char[,] parContractString;


    }
}

dllimport 调用函数:

[DllImport("dds.dll")]
        public static extern int Par(DdTableResults tablep, int vulnerable, ParResults parResults);

知道我可以做些什么来让它工作吗?

非常感谢!

【问题讨论】:

  • c# 签名与您提供给我们的 c++ 签名不匹配:public static extern int Par(DdTableResults tablep, int vulnerable, ParResults parResults); vs struct ddTableResults *tablep, struct parResults *presp, int vulnerable(交换了第 2 和第 3 个参数)
  • 感谢您的回复。我现在已经切换了参数,但它仍然会导致 SystemViolation 异常。

标签: c# c++ dll


【解决方案1】:

据我了解,你的 c++ 签名是

int Par(struct ddTableResults *tablep, struct parResults *presp, int vulnerable)

c# 可能是

[DllImport("dds.dll")]
public static extern int Par(ref DdTableResults tablep, ref ParResults parResults, int vulnerable);

c++ 想要一个指向DdTableResultsParResults 的指针,没有ref c# 将按值传递结构。

【讨论】:

  • 非常感谢,这解决了访问冲突问题,这使我能够非常快速地调试程序的其余部分并让程序运行!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多