从托管 C++ 调用本机 C++ 代码的 AccessViolationException(ASP.NET 的包装器)

AccessViolationException calling native C++ code from managed C++ (wrapper for ASP.NET)

我有一个 ASP.NET Web 应用程序需要访问本机 C++ DLL 中的函数。为此,我使用托管 C++ DLL 包装了本机 C++ 代码。但是,从托管代码调用本机函数会导致 System.AccessViolationException。我不需要本机代码,但它会写入文件系统(日志),这是我的第一个猜测,但根据其他 SO 答案,AccessViolationException 是由内存问题引起的。

代码很简单,这是未精简版:

#include <msclr\marshal_cppstd.h>

#define AS_NATIVE_STRING(managed_string) msclr::interop::marshal_as<std::string>(managed_string)
#define AS_MANAGED_STRING(native_string) msclr::interop::marshal_as<String^>(native_string)

ReturnStruct ManagedClass::execute_managed(String ^param1, String ^param2)
{
    auto param1_native = AS_NATIVE_STRING(param1);
    auto param2_native = AS_NATIVE_STRING(param2);

    // here I get the exception:
    auto result = _wrapped_api->execute_native(param1_native, param2_native);

    if (is_error_string(result.first))
        throw gcnew System::Exception(AS_MANAGED_STRING(result.second));

    auto result1 = AS_MANAGED_STRING(result.first);
    auto result2 = AS_MANAGED_STRING(result.second);
    return ReturnStruct(result1, result2);
}

关于可能导致它的原因的任何提示?我确实看过类似的问题,但似乎没有答案真正适合我的问题。

编辑: 使用 HandleProcessCorruptedStateExceptionsAttribute 我能够确定 AccessViolationException 的错误消息:"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

经过进一步调查,我得出结论,我基本上无法解决这个问题。我自己创建了一个 DLL 的模拟版本,以便能够介入并查看类型转换是否正确以及参数是否包含正确的字符串。是这样的。这并没有真正帮助我,但也许其他人可能会在 his/her 代码中使用这种方法发现问题。

我只会联系包装的作者api。