显式从非托管c ++调用托管析构函数

时间:2013-01-21 17:28:30

标签: c++ .net interop destruction

我有一个本机C ++项目,它通过包装类使用.NET图表实用程序。包装类的简化版本是这样的;

class ChartWrapper
{
private:
    gcroot<ChartNamespace::ManagedChartClass^>* m_Chart;

public:
    ChartWrapper(): m_Chart(new gcroot<ChartNamespace::ManagedChartClass^>)
    {
        *m_Chart = gcnew ChartNamespace::ManagedChartClass;
    }

    ~ChartWrapper()
    {
        delete m_Chart;
    }

    // Methods to interact with the chart
}

一个函数将负责通过包装器实例化,操作和删除图表;

void CreateChart()
{
    ChartWrapper* chart = new ChartWrapper();
    // Do stuff to the chart
    delete chart;
}

在程序实例中可能会创建数百个图表。我完成后,通过调用delete显式删除每个包装器,但是只有在程序退出时才会销毁托管对象ManagedChartClass。这会导致不需要的内存构建,并且我会“内存不足”的例外情况。

如何在包装器被破坏时确保被管理对象被破坏?

1 个答案:

答案 0 :(得分:3)

您可以使用auto_gcroot<T>代替gcroot<T>。区别在于auto_gcroot<T>的{​​{3}}“也会破坏拥有的对象。”

在托管环境中,只要它实现IDisposable.Dispose(),就会映射到包装托管类型上的IDisposable

相关问题