繁体   English   中英

是否可以通过 Cython 通过引用从 Python 到 C++ 传递值?

[英]Is it possible to pass values by reference from Python to C++ via Cython?

是否可以创建一个包含指向 Python 变量的指针的 C++ object? 我担心的是 Python 变量是 PyObject ,因此 C++ 无法正确读取它。

举个例子,这里是来自官方Cython 网站的教程,针对我的问题略有改动。 main.py 的结果是错误的

Main.py(其中使用了 Rectangle object)

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM