【问题标题】:DllImport causing access violation exceptionDllImport 导致访问冲突异常
【发布时间】:2018-12-07 09:52:35
【问题描述】:

C dll 头是这样的:

HRESULT App_Process(char *FileName, char *Output, const bool& LogInformation);

我的 C# DllImport 如下所示:

[DllImport("App.dll")]
public static extern Int32 App_Process(
    [MarshalAs(UnmanagedType.LPStr)]string FileName,
    [MarshalAs(UnmanagedType.LPStr)]string Output,
    [MarshalAs(UnmanagedType.Bool)]bool LogInformation);

例外是:

var result = App_Process("MyFile.txt", "Output.txt", true);

System.AccessViolationException:试图读或写保护 记忆。这通常表明其他内存已损坏。

现在奇怪的是,该方法成功地完成了它应该做的所有事情。

有什么想法吗?

【问题讨论】:

  • 也许最后一个参数应该是ref bool?
  • 所有MarshalAs 属性都是没有意义的,只是像它们一样重申默认值。最后一个参数是ref bool。调用约定未知。看起来这两个字符串参数可能是输出参数,因为它们是char* 而不是const char*。我建议您在尝试调用它之前阅读该库的文档。
  • @DaisyShipton 是的,ref bool 解决了这个问题。请发布它作为答案。谢谢。

标签: c# dllimport unmanaged access-violation managed


【解决方案1】:

原答案

extern 方法的最后一个参数应该是ref bool 而不是bool,因为DLL 标头有一个const bool& 类型的参数:

// Parameter names changed to be idiomatic for C#
[DllImport("App.dll")]
public static extern Int32 App_Process(
    [MarshalAs(UnmanagedType.LPStr)] string fileName,
    [MarshalAs(UnmanagedType.LPStr)] string output,
    [MarshalAs(UnmanagedType.Bool)] ref bool logInformation);

对于 C# 7.2,我怀疑您可以使用 in 而不是 ref,这将使该方法更易于调用:

// Parameter names changed to be idiomatic for C#
[DllImport("App.dll")]
public static extern Int32 App_Process(
    [MarshalAs(UnmanagedType.LPStr)] string fileName,
    [MarshalAs(UnmanagedType.LPStr)] string output,
    [MarshalAs(UnmanagedType.Bool)] in bool logInformation);

更新

(来自 Hans Passant 的评论)

这不是 C 代码,因为 bool& 仅在 C++ 中有效。这使得该参数很可能需要编组为[MarshalAs(UnmanagedType.U1)]。在本机代码中使用 sizeof(bool) 仔细检查。但是您应该与 DLL 的作者交谈,因为 const bool& 根本没有意义。通过引用传递布尔值但不允许代码更新它是没有意义的。

【讨论】:

  • 这不是 C 代码,bool& 仅在 C++ 中有效。这使得该论点很可能需要 [MarshalAs(UnamagedType.U1)]。在本机代码中使用 sizeof(bool) 仔细检查。 OP 真的 需要和作者交谈, const bool& 根本没有意义。通过引用传递布尔值但不允许更新它是没有意义的。
  • @HansPassant:我已经更新了答案,几乎逐字包含您的评论。我们会看看 OP 是否看到它......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
相关资源
最近更新 更多