简体   繁体   English

swig 接口文件中未调用 C++ 析构函数

[英]C++ destructor not being called in a swig interface file

I am creating an interface between c++ and python code.我正在创建 C++ 和 python 代码之间的接口。

I create a module called composition_api in a swig interface file.我在 swig 接口文件中创建了一个名为composition_api的模块。 It has methods that I import into a python module as shown below.它具有我导入到 python 模块中的方法,如下所示。

/// SWIG Interface File.
%module composition_api
%{
    #include <include/mcm/compiler/compilation_unit.hpp>


    mv::CompilationUnit* getCompilationUnit(bool disableHardware)
    {
        auto unit = new mv::CompilationUnit("pySwigCU");
             return unit;
    }
}

I import this as library into a python script.我将它作为库导入到 python 脚本中。

Python script Python脚本

import composition_api as ca
compUnit = ca.getCompilationUnit(not enableHardware)

When the python script is finished running the CompilationUnit destructor is not being called in the C++ source code.当 python 脚本运行完毕后,C++ 源代码中不会调用CompilationUnit析构函数。 Do I have to create a method in the interface file that calls delete unit ?我是否必须在接口文件中创建一个调用delete unit

The C++ counterpart of compUnit is a pointer. compUnit的 C++ 对应物是一个指针。 When compUnit is garbage collected by Python, it simply garbage collects the pointer.compUnit被 Python 垃圾收集时,它只是简单地垃圾收集指针。 It does not automatically call delete on the pointer.它不会自动调用指针上的delete

You have couple of choices that I can think of.你有几个我能想到的选择。

  1. Return an object to Python that is wrapper to the pointer.将一个对象返回给 Python,该对象是指针的包装器。 When the object gets garbage collected, its destructor will be called.当对象被垃圾回收时,它的析构函数将被调用。 Add the necessary code to delete the C++ object in the destructor of the wrapper.在包装器的析构函数中添加必要的代码以删除 C++ 对象。

  2. Add an explicit function in the swig interface file to delete the object.在 swig 接口文件中添加显式函数删除对象。 Make sure to call the function in Python before the scope of the Python object ends.确保在 Python 对象的范围结束之前在 Python 中调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM