如何使用结构解决托管 C# 代码中的访问冲突?

How can I resolve an access violation in managed C# code with structs?

问题: 当我尝试访问 C# struct 的派生 属性 时,会导致访问冲突错误并且应用程序突然退出(状态为 0xC0000005)。与 this question 不同,它确定性地发生在单个 属性.

结构定义在不同的库中,但我同时控制客户端应用程序和定义结构的库。

我没有为这个项目编写非托管代码。我在客户端应用程序和库中都使用 .NET 5。

我尝试过的事情:

  1. 将库中的输出更改为 x64 没有帮助(应用程序输出是 x64)
  2. 启用本机代码调试(未提供任何信息)

MCVE:

定义

public struct Foo
{
    public const Double BarDivisor = 100.0;

    // ...other properties...

    public Int64 BarWholePart { get; }
    public Int64 BarFractionalPart { get; }
    public Double Bar => Bar + (BarFractionalPart / BarDivisor);
    
    public Foo(Int64 wholePart, Int64 fractionalPart, /* ... */)
    {
        // ...
        BarWholePart = wholePart;
        BarFractionalPart = fractionalPart;
    }

    public static Foo Parse(Int64 whole, Int64 fractional)
    {
        return new Foo(whole, fractional);
         // ...
    }
}

调用代码示例

public void Baz(Foo bar)
{
    // ...
    Double foobar = bar.Bar; // this line results in a crash of the application
    // ...
}

异常消息:

Exception thrown at 0x00007FF8C85A21A0 (coreclr.dll) in [application name removed]: 0xC0000005: Access violation writing location 0x000000E70B180FF8.

The Common Language Runtime cannot stop at this exception. Common causes include: incorrect COM interop marshalling and memory corruption. To investigate further use native-only debugging.

Unhandled exception at 0x00007FF8C85A21A0 (coreclr.dll) in [application name removed]: 0xC0000005: Access violation writing location 0x000000E70B180FF8.

The Common Language Runtime cannot stop at this exception. Common causes include: incorrect COM interop marshalling and memory corruption. To investigate further use native-only debugging.

这是由于此处的印刷错误造成的

public Double Bar => Bar + (BarFractionalPart / BarDivisor);
应使用

BarWholePart 而不是 Bar。这会导致 WhosebugException,但有时会在调试器中导致 AccessViolationException。