簡體   English   中英

麻煩析構函數,用boost.python中的指針調用python的對象

[英]Trouble destructor,call python's object with pointer in boost.python

當我在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)
    ;
}

蟒蛇:

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”中嘗試,有一些錯誤。我只想運行析構函數一次。怎么辦?

為了理解真正發生的事情,你錯過了一個拷貝構造函數:

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函數和方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM