简体   繁体   English

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

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

Is it possible to create a C++ object that contains a pointer to a Python variable?是否可以创建一个包含指向 Python 变量的指针的 C++ object? My concern is that the Python variable is a PyObject and thus there is no way that C++ could read it properly.我担心的是 Python 变量是 PyObject ,因此 C++ 无法正确读取它。

To make an example, here is the tutorial from the official Cython website slightly altered for my question.举个例子,这里是来自官方Cython 网站的教程,针对我的问题略有改动。 The results from main.py are wrong main.py 的结果是错误的

Main.py (where the Rectangle object is used) 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())

Result结果

-403575482
-407128282

Rectangle.cpp矩形.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);
    }
}

For the sake of clarity, I did not post the other files as I do not think they are necessary for understanding my question.为了清楚起见,我没有发布其他文件,因为我认为它们对于理解我的问题不是必需的。

On performing some experiments I found a solution, where you have to explicitly call the cinit method that you have defined in the .pyx file.在执行一些实验时,我找到了一个解决方案,您必须显式调用您在.pyx文件中定义的cinit方法。

The new python file would look something like this新的 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())

and your .pyx looks as this你的.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