SWIG-包装STD ::一对串时的内存泄漏

SWIG - memory leak when wrapping std::pair of strings

本文关键字:内存 泄漏 包装 STD SWIG-      更新时间:2023-10-16

我试图用swig to python包装std ::映射,除了它泄漏内存(我的代码下面)。

显然,Swig自动释放返回的对象的(Tuple)内存,但不能释放其中分配的String。我读到我可以使用%typemap(newfree)使用明确的Deadlocation,但不知道如何实现。

%typemap(out) std::pair<std::string, double> {
    $result = PyTuple_Pack(2, PyUnicode_FromString($1.first.c_str()), 
                              PyFloat_FromDouble($1.second));
};
%typemap(newfree) std::pair<std::string, double> {
     // What to do here?
     // delete[] $1.first.c_str() clearly not the way to go...
}

swig具有 pairstring的预定类型,因此您无需自己写它们:

test.i

%module test
// Add appropriate includes to wrapper
%{
#include <utility>
#include <string>
%}
// Use SWIG's pre-defined templates for pair and string
%include <std_pair.i>
%include <std_string.i>
// Instantiate code for your specific template.
%template(sdPair) std::pair<std::string,double>;
// Declare and wrap a function for demonstration.
%inline %{
    std::pair<std::string,double> get()
    {
        return std::pair<std::string,double>("abcdefg",1.5);
    }
%}

演示:

>>> import test
>>> p = test.sdPair('abc',3.5)
>>> p.first
'abc'
>>> p.second
3.5
>>> test.get()
('abcdefg', 1.5)