【问题标题】:Debug assertion failed error when passing std::string from c++/cli dll to native win32 dll将 std::string 从 c++/cli dll 传递到本机 win32 dll 时调试断言失败错误
【发布时间】:2023-03-07 17:16:01
【问题描述】:

我有一个 C# 表单调用一个 c++/cli 接口 DLL,它调用一个 win32 本机 c++ dll。最初这是用 VS2010 编写的,并且正在工作 - 我能够将 System::String 编组为 std::string,将其传递给本机 dll,然后计算出值。然后我将 C# 和 c++/cli 项目转换为 VS2012 以启用智能感知。这需要安装服务包以重新启用 VS2010 中的 4.0 .NET 框架。我在 2010 年重建了 Win32 dll,在 VS2012 中重建了 C# 应用程序和 c++/cli dll,现在我在调用 dll 时收到错误:

调试断言失败!

程序: ... 文件:f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c 线路:1424

表达式:_pFirstBlock == pHead

public ref class ManagedWrapper
{
    CSampleWin32Library* m_pUnmanagedWrapper;


public:
    ManagedWrapper() {m_pUnmanagedWrapper = new CSampleWin32Library();}
    ~ManagedWrapper() {delete m_pUnmanagedWrapper;}

    //Test call to prove integration
    void Test(int x, System::String^ testString) {
        //marshaling example: http://msdn.microsoft.com/en-us/library/bb384865.aspx         
        std::string tmpStdString = marshal_as<std::string>(testString);
        m_pGambitUnmanagedWrapper->Test(x, tmpStdString); //ERROR OCCURS HERE
    };      
};

希望这与丢失的某些设置一样简单,或者现在在 VS2012 中是必需的。据我所知,我没有更改任何代码。

【问题讨论】:

  • 跨 DLL 边界传递 C++ 对象很麻烦。提醒您,您的 C++/CLI DLL 不使用与 C++ DLL 相同版本的 CRT。您必须重建 C++ DLL,以便它使用 VS2012 版本的 CRT,确保 /MD 有效。通过引用而不是值传递 std::string 进一步改进 Test()。
  • 谢谢汉斯。您介意将此作为答案提交,以便我接受吗?
  • 这只是一个猜测,问题中几乎没有表明这是问题的真正原因。您最好发布自己的答案并准确描述您的发现。

标签: c++-cli


【解决方案1】:

这个错误主要是因为你在堆 A 中 malloc 的一块内存在堆 B 中被释放了。

您应该看看Windows Via C/C++--第四部分动态链接库。

应用程序在运行时会调用 CRT。

调用 CRT 有两种方法——链接到 DLL C/C++ 运行时库或链接到静态 C/C++ 运行时库以及不同版本的 CRT。

它们都使用不同的内存管理。

因此,在释放内存和链接到 DLL 的代码时应该小心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多