通过引用

时间:2017-11-21 04:02:59

标签: python c++ pointers pass-by-reference boost-python

问题是如下。 说,我有一个通过 Boost.Python 向Python公开的类Matrix。 现在,这是另一个类Calcs

class Calcs
{
public:
    Matrix* x;
    Matrix* res;

    Calcs(){ x = NULL; res = NULL; }

    void set_x(Matrix& x_){ x = &x_; }
    void set_res(Matrix& res_){ res = &res_; }

    void run_calc(){ *res = *x; }
    Matrix get_res(){ return *res; }
};

Python的用法是:

x = Matrix(2,2)  # this will allocate memory for the matrix x
y = Matrix(2,2)  # same for y

c = Calcs() 
c.set_x(x)     # so now the internal pointer of the c object points to the 
               # location of the object x
c.set_res(y)   # same for y
c.run_calc()   # so now, we should be able to look at the object y and find 
               # the result stored in it, but it reality this object 
               # is not actually changed
c.get_res()    # this will give the answer as expected

正如Python脚本的注释所示,使用模式是在外部对象中分配内存(输入和结果),然后使Calcs对象中的指针指向这些位置,运行计算,然后在y中准备好结果。但不知怎的,这不起作用,我很难理解为什么。

好的一面是,每当我更新输入矩阵x并使用函数get_res()返回结果时,结果每次都会更新,因此会更新x的值。

尽管如此,矩阵y并未改变其内容。我认为Python可能正在创建一些中间对象,所以当我在C ++中更新y时,只有那个中间对象看到变化,这就是对象{{1没有更新。

所以,我想知道这是否正确理解以及我如何解决这个问题。

0 个答案:

没有答案
相关问题