尝试读取或写入受保护的内存异常发生 w/o 调试但未 w/debugging

Attempted to read or write protected memory exception occurs w/o debugging but not w/debugging

肯定有人问过这个问题的衍生问题,但我还没有找到符合我的情况的问题。

我创建了一个库,它封装了第三方 C++ 库并将其提供给一些内部系统。创建的库使用 C++/CLI 允许用户通过 C# 访问它。该库可以使用我们内部的持续集成 NuGet 服务器构建并启动,因此可以使用。

当 运行 使用 "Start Debugging" (F5) 运行程序时,在其他 application/system 中使用此库没有问题,但只要 运行 使用 "Start Without Debugging" (Ctrl+F5) 或通过可执行文件引发以下异常:

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

at TheirLib.func(Int32 , Int32 , Double* , Int32 , Int32* , Int32* , Double* , Int32 , TheirLibError* )
at MyLib.Func(Int32 n, Int32 m, Double[] x, Int32 tdx, Int32[] svar, Int32[] sobs, Double[] corr, Int32 tdc)
at SomeApplication.Program.Main(String[] args) in d:\SomeApplication\SomeApplication\Program.cs:line 67

我在这里 (https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception) 读到可能需要 .NET 4.5.2,但这并没有改变任何东西。我还认为我的 C++/CLI 库中可能有一些设置可以让我规避这个问题,但我一直找不到任何东西,我觉得我到处都找过了。我还查看了准备调用第三方库时使用的 pin_ptr 对象的 C++/CLI 代码,但一切看起来都很好(见下文)。

void MyLib::Func(int n, int m, array<double>^ x, int tdx, array<int>^ svar, array<int>^ sobs,
    array<double>^ corr, int tdc)
{
    // Setup input parameters
    pin_ptr<double> xPtr = &(x[0]);
    pin_ptr<int> svarPtr = &(svar[0]);
    pin_ptr<int> sobsPtr = &(sobs[0]);
    pin_ptr<double> corrPtr = &(corr[0]);
    TheirLibError fail;

    // Call their library's function
    func(n, m, xPtr, tdx, svarPtr, sobsPtr, corrPtr, tdc, &fail);
}

同样,该库在 "Start Debugging" 下完全按照预期工作,并通过了一组详尽的测试,但我只是不明白为什么这不能独立工作...此时我会尝试任何东西让它工作。帮帮我,你是我唯一的希望...

联系库所有者后,问题是 TheirLibError 未正确初始化,并且此结构中包含的指针未在库中正确处理。正确初始化后,一切正常。

故事的寓意,向库所有者询问他们的库在遇到 AccessViolationException 时是否保留指针或任何其他指针行为。