python - 是否可以通过 Cython 通过引用将值从 Python 传递到 C++?
问题描述
是否可以创建一个包含指向 Python 变量的指针的 C++ 对象?我担心的是 Python 变量是 PyObject,因此 C++ 无法正确读取它。
举个例子,这里是来自官方Cython 网站的教程,针对我的问题略有改动。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);
}
}
为了清楚起见,我没有发布其他文件,因为我认为它们对于理解我的问题不是必需的。
解决方案
在执行一些实验时,我找到了一个解决方案,您必须显式调用您在 .pyx 文件中定义的cinit方法。
新的 python 文件看起来像这样
import rect
x0, y0, x1, y1 = 1, 2, 3, 4 \
rect_obj = rect.PyRectangle() \
rect_obj._cinit_(x0, y0, x1, y1) \
print(rect_obj.get_size()) \
print(rect_obj.get_area())
你的.pyx看起来像这样
from Rectangle cimport Rectangle
cdef class PyRectangle:
cdef Rectangle c_rect
def _cinit_(self, int x0, int y0, int x1, int y1):
self.c_rect = Rectangle(x0, y0, x1, y1)
def get_area(self):
return self.c_rect.getArea()
def get_size(self):
cdef int width, height
self.c_rect.getSize(&width, &height)
return width, height
def move (self, dx, dy):
self.c_rect.move(dx, dy)
推荐阅读
- python - 我如何向不和谐请求添加附件?
- json - 在 delphi-xe 中使用 NetHTTPClient1 发布带有身份验证的 json
- python - 如何修复“CSRF 验证失败。请求中止。” 请?
- flutter - 错误:无法处理本地通知上的方法调用
- docker - 向 Traefik 添加自定义标头会产生奇怪的行为
- javascript - 对象构造函数,将信息从表单传递到 HTML
- python - 如何洗牌html字段?- django
- css - 图像周围的阴影效果而不是图像边框
- xml - Delphi 使用 XML 格式的 Rest Client 示例
- php - 如何在 bemusic 中增加服务器文件上传限制?