簡體   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