c++ - 将 System::String 转换为 std::string 时,std::string delete 运算符出现运行时异常

标签 c++ c++-cli clr marshalling stdstring

我将 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);
}

最佳答案

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

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

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

因此,您尝试绑定(bind)一个使用 release 编译的 dll 作为配置。 但是现在您尝试找出一些东西,使用调试,现在忘记了您的运行时 dll 不匹配然后您的代码正在使用调试信息创建它,但是 您将此对象提供给 native/cpp 函数,该函数是使用 release 编译的,并尝试释放该对象,但该对象不起作用。或者反之亦然,通过调试删除释放 std:string。

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

关于c++ - 将 System::String 转换为 std::string 时,std::string delete 运算符出现运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350306/

相关文章:

programming-languages - CLR 上的功能开发

.net - 是asp.net和.net框架版本相同?还是asp.net或clr版本都一样?

c++ - std::string 的默认容量?

c++ - CVMat : sizes of input arguments do not match

使用 shared_ptr 作为参数时的 C++/CLI "could not import member"警告

windows - C++ -'Stream' 未声明的标识符

c++ - ref类c++中的动态多维数组

c++ - Makefile vpath 不适用于头文件

c++ - 如果没有预处理步骤,Qt 的可用性如何?

.net - 何时以及为什么需要supportedRuntime 元素和sku 属性?