相关疑难解决方法(0)

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

我正在尝试使用boost::shared_ptr's允许我在我的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')


%}
Run Code Online (Sandbox Code Playgroud)

这是警告:

In [2]: ptrtest.leak_memory()
swig/python detected a memory leak of type 'ofstream_ptr *', …
Run Code Online (Sandbox Code Playgroud)

c++ python file-io swig memory-leaks

8
推荐指数
1
解决办法
2681
查看次数

Python 3替换PyFile_AsFile

以下代码适用于Python 2:

from ctypes import *

## Setup python file -> c 'FILE *' conversion :
class FILE(Structure):
    pass
FILE_P = POINTER(FILE)
PyFile_AsFile = pythonapi.PyFile_AsFile # problem here
PyFile_AsFile.argtypes = [py_object]
PyFile_AsFile.restype = FILE_P
fp = open(filename,'wb')
gd.gdImagePng(img, PyFile_AsFile(fp))
Run Code Online (Sandbox Code Playgroud)

但在Python 3中,pythonapi中没有PyFile_AsFile.

代码是testPixelOps.py之外的代码.

python ctypes ffi python-3.x

7
推荐指数
1
解决办法
1878
查看次数

标签 统计

python ×2

c++ ×1

ctypes ×1

ffi ×1

file-io ×1

memory-leaks ×1

python-3.x ×1

swig ×1