当我在boost.python中以指针作为参数调用python函数时,析构函数出现了一些问题。以下是示例代码
C++
#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <string>
#include <iostream>
using namespace boost::python;
class A {
public:
A() {
std::cout<< "A start"<<std::endl;
}
~A() {std::cout<< "A end" <<std::endl;}
}
class B {
public:
B() { aa=new A; }
~B() { delete aa; }
void run(object ct) {
_obj=ct(); //creat a python object
_obj.attr("fun1")(aa); //call a function named "fun1" with a pointer arg
_obj.attr("fun2")(aa); //call a function named "fun2" with a pointer arg
}
A *aa;
object _obj;
}
BOOST_PYTHON_MODULE(ctopy)
{
class_<A> ("A",init<>())
;
class_<b> ("B",init<>())
.def("run",&B::run)
;
}
Python:
import ctopy
class tc:
def fun1(self,tt):
print "fun1"
def fun2(self,tt):
print "fun2"
bb=ctopy.D()
bb.run(tc)
这个结果:
A start
fun1
A end
fun2
A end
A end
笔记:
“A end”已经打印了三个。我在“valgrind”中试了一下,有一些错误。我只想运行一次析构函数。怎么办?