簡體   English   中英

如何使用shared_ptr和SWIG避免內存泄漏

[英]How to avoid memory leak with shared_ptr and SWIG

我正在嘗試使用boost::shared_ptr來允許我在我的python腳本中使用c ++文件I / O流對象。 但是,生成的包裝器警告我它正在泄漏內存。

這是一個顯示問題的最小.i文件:

%module ptrtest

%include "boost_shared_ptr.i"
%include "std_string.i"

%shared_ptr( std::ofstream )

%{
#include <fstream>
#include <boost/shared_ptr.hpp>

typedef boost::shared_ptr< std::ofstream > ofstream_ptr;

ofstream_ptr mk_out(const std::string& fname ){
    return ofstream_ptr( new std::ofstream( fname.c_str() ) );
}

%}

ofstream_ptr mk_out(const std::string& fname );


%pythoncode %{

def leak_memory():
    ''' demonstration function -- when I call
        this, I get a warning about memory leaks
    ''''
    ostr=mk_out('/tmp/dont_do_this.txt')


%}

這是警告:

In [2]: ptrtest.leak_memory()
swig/python detected a memory leak of type 'ofstream_ptr *', no destructor found.

有沒有辦法修改.i文件告訴接口如何正確處理shared_ptr?

您的示例缺少兩部分來運行析構函數:

  1. 由於SWIG對std::ofstream一無所知,因此默認行為除了傳遞一個不透明的句柄之外什么都不做。 請參閱我的另一個答案,以進一步討論此問題。

    這里的修復是為你的接口文件中的std::ofstream提供一個空的定義,以說服SWIG它知道足夠多做更多,即使你不打算暴露任何成員。

  2. SWIG需要查看typedef本身 - 在%{ %}內部它直接傳遞給輸出模塊,而不是在包裝本身中使用。

因此,您的示例變為:

%module ptrtest

%include "boost_shared_ptr.i"
%include "std_string.i"

%shared_ptr( std::ofstream )

namespace std {
  class ofstream {
  };
}

%{
#include <fstream>
#include <boost/shared_ptr.hpp>

typedef boost::shared_ptr< std::ofstream > ofstream_ptr;

ofstream_ptr mk_out(const std::string& fname ){
    return ofstream_ptr( new std::ofstream( fname.c_str() ) );
}
%}

typedef boost::shared_ptr< std::ofstream > ofstream_ptr;
ofstream_ptr mk_out(const std::string& fname );

%pythoncode %{
def leak_memory():
    ostr=mk_out('/tmp/dont_do_this.txt')
%}

為了將來參考,您可以避免重復只存在於帶有%inline的.i文件中的內容:

%inline %{
typedef boost::shared_ptr< std::ofstream > ofstream_ptr;

ofstream_ptr mk_out(const std::string& fname ){
    return ofstream_ptr( new std::ofstream( fname.c_str() ) );
}
%}

其中一次聲明,定義和包裝它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM