3

当我在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”中试了一下,有一些错误。我只想运行一次析构函数。怎么办?

4

1 回答 1

2

要了解真正发生的事情,您缺少一个复制构造函数:

B()
  A()
B::run()
  A(a)     <- copy construct A to pass by value
    fun1() <- arg passed by value
  ~A()     <- delete copy
  A(a)     <- copy construct A to pass by value
    fun2() <- arg passed by value
  ~A()     <- delete copy
~B()
  ~A()

在您的示例中,aa按值传递,这就是副本的来源。不管是否aa是指针,boost 都会将其转换为传递给 python 方法的对象。

如果你想避免额外的副本,A你可以通过aa 引用而不是通过值传递:

_obj.attr("fun1")(boost::ref(aa));
_obj.attr("fun2")(boost::ref(aa));

这将导致:

B()
  A()    <- constructed once
B::run()
  fun1() <- arg passed by reference
  fun2() <- arg passed by reference
~B()
  ~A()   <- destroyed once

有关详细信息,请参阅调用 Python 函数和方法

于 2012-12-23T02:57:52.307 回答