SWIG - 包装字符串 std::pair 时发生内存泄漏
SWIG - memory leak when wrapping std::pair of strings
我正在尝试使用 SWIG 将 std::map 包装到 python,并且它工作得很好,除了它会泄漏内存(下面我的代码)。
显然 SWIG 会自动释放返回对象的(Tuple
)内存,但不会释放其中分配的 String
。我读到我可以使用 %typemap(newfree)
来使用显式释放,但不知道如何实现。
%typemap(out) std::pair<std::string, double> {
$result = PyTuple_Pack(2, PyUnicode_FromString(.first.c_str()),
PyFloat_FromDouble(.second));
};
%typemap(newfree) std::pair<std::string, double> {
// What to do here?
// delete[] .first.c_str() clearly not the way to go...
}
SWIG 为 pair
和 string
预定义了类型映射,因此您无需自己编写它们:
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)
我正在尝试使用 SWIG 将 std::map 包装到 python,并且它工作得很好,除了它会泄漏内存(下面我的代码)。
显然 SWIG 会自动释放返回对象的(Tuple
)内存,但不会释放其中分配的 String
。我读到我可以使用 %typemap(newfree)
来使用显式释放,但不知道如何实现。
%typemap(out) std::pair<std::string, double> {
$result = PyTuple_Pack(2, PyUnicode_FromString(.first.c_str()),
PyFloat_FromDouble(.second));
};
%typemap(newfree) std::pair<std::string, double> {
// What to do here?
// delete[] .first.c_str() clearly not the way to go...
}
SWIG 为 pair
和 string
预定义了类型映射,因此您无需自己编写它们:
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)