【发布时间】:2021-05-10 11:13:30
【问题描述】:
是否可以创建一个包含指向 Python 变量的指针的 C++ 对象?我担心 Python 变量是 PyObject,因此 C++ 无法正确读取它。
举个例子,这里是官方Cython website的教程,针对我的问题稍作改动。 main.py 的结果是错误的
Main.py(使用 Rectangle 对象的地方)
import rect
x0, y0, x1, y1 = 1, 2, 3, 4
rect_obj = rect.PyRectangle(x0, y0, x1, y1)
print(rect_obj.get_area())
x0 = 10 # change value PyRectangle points to
print(rect_obj.get_area())
结果
-403575482
-407128282
矩形.cpp
#include <iostream>
#include "Rectangle.h"
namespace shapes {
// Overloaded constructor
Rectangle::Rectangle (int x0, int y0, int x1, int y1) {
this->x0 = &x0;
this->y0 = y0;
this->x1 = x1;
this->y1 = y1;
}
// Return the area of the rectangle
int Rectangle::getArea () {
return (this->x1 - *(this->x0)) * (this->y1 - this->y0);
}
}
为了清楚起见,我没有发布其他文件,因为我认为它们对于理解我的问题没有必要。
【问题讨论】:
-
用
&x0获取的指针在构造函数返回后立即失效,因为它是参数的地址。 -
有道理。我猜我太习惯 Python了。
-
这在 Python 中也不起作用;分配给
x0对除该变量之外的任何内容都没有影响。 -
这取决于你传递给对象的内容。在这种情况下,你是对的。在做了一些研究之后,我找不到解决我的问题的方法。因此,我也将在 C++ 中声明和定义 x0,并编写一个函数来用 Python 更改它。感谢您的帮助!
-
“因此 C++ 无法正确读取它”——Python C API 正是为此目的。 Python 整数是不可变的(通常也是“单例”)。