代码之家  ›  专栏  ›  技术社区  ›  Mugen

将System::string转换为std::string时,std::string delete运算符中出现运行时异常

  •  1
  • Mugen  · 技术社区  · 7 年前

    我正在使用 C++ cli 同时使用这两种解决方案 C# C++ 密码

    当我尝试转换时 System::String std::string 每次运行时,我都会遇到以下运行时异常:

    ucrtbased.dll!00007ffd9902b9b0()    Unknown
    ucrtbased.dll!00007ffd9902eac5()    Unknown
    MyApp.dll!operator delete(void * block) Line 21 C++
    [Managed to Native Transition]  
    MyApp.dll!std::_Deallocate(void* _Ptr, unsigned __int64 _Count, unsigned __int64 _Sz) Line 133  C++
    MyApp.dll!std::allocator<char>::deallocate(char* _Ptr, unsigned __int64 _Count) Line 721    C++
    MyApp.dll!std::_Wrap_alloc<std::allocator<char> >::deallocate(char* _Ptr, unsigned __int64 _Count) Line 988 C++
    MyApp.dll!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Tidy(bool _Built, unsigned __int64 _Newsize) Line 2260 C++
    MyApp.dll!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::=(std::basic_string<char,std::char_traits<char>,std::allocator<char> >& _Right) Line 934    C++
    MyApp.dll!MyApp::DoStuff(System::String^ input) Line 59 C++
    

    或者在没有调试器的情况下运行时:

    error

    我的代码,我尝试了两种选择,都导致了相同的崩溃:

    选项1

    void MyApp::DoStuff(System::String^ input) {
        msclr::interop::marshal_context context;
        std::string converted = context.marshal_as<const char*>(LicenseOEM);
    }
    

    选项2

    std::string SystemToStd(System::String^ sys) {
        int len = sys->Length;
        char* buff = (char*)malloc((len + 1) * sizeof(char));
        for (int i = 0; i < sys->Length; i++) {
            buff[i] = sys[i];
        }
        buff[len] = '\0';
        std::string str = std::string(buff, len);
        free(buff);
        return str;
    }
    
    void MyApp::DoStuff(System::String^ input) {
        std::string converted = SystemToStd(LicenseOEM);
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   JackGrinningCat    7 年前

    也许这本身就是一个C++主题。

    您是否确保为您的配置绑定正确/合适/相同的运行时DLL。

    微软的调试DLL(其他我不知道)试图找出是否有人破坏了内存。 它们通过提供不同的new/delete实现来实现。 基本上,它们会扩大分配的内存,以便在分配内存之前和之后都有未使用的内存。然后他们用模式和信息填充它,并给你指向对象的指针。删除/释放对象时,它们会为您的存储区域获得正确的值,并控制信息,以及是否有人覆盖了对象前后的模式。

    因此,您尝试绑定一个以release作为配置编译的dll。 但现在您试图找到一些东西,使用debug,现在忘记运行时DLL 不匹配 然后,您的代码将使用调试信息创建它,但是 您将此对象提供给本机/cpp函数,该函数是使用release编译的,并尝试释放该对象,但该函数不起作用。反之亦然,release std:使用debug delete释放字符串。

    实际上,我在谷歌上搜索了你的失败消息和一些相同方向的提示,所以你可以重新检查 Debug Assertion Failed! Expression: __acrt_first_block == header