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

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

本文关键字:包装 调用 代码 本机 NET ASP AccessViolationException      更新时间:2023-10-16

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

代码非常简单,这是未交换版本:

#include <msclrmarshal_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的错误消息:"尝试读取或写下受保护的内存。这通常表明其他内存是损坏的。"

进一步调查后,我得出的结论是,我基本上无法在我的末尾解决这个问题。我本人创建了DLL的模拟版本,以便能够介入并查看类型转换是否正确,并且参数包含正确的字符串。就是这样。这并没有真正帮助我,但是也许其他人可能会在他/她的代码中找到问题。

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