SWIG-包装STD ::一对串时的内存泄漏
SWIG - memory leak when wrapping std::pair of strings
我试图用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具有 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)
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏