赛通示例中的语法错误

Syntax Error in Cython Example

本文关键字:语法 错误      更新时间:2023-10-16

我正在尝试在此页面上构建一个Cython示例。

我知道我的帖子与另一个问题非常相似。但是,我生成了完全不同的错误消息。

这是我的代码:

矩形.cpp

#include "Rectangle.h"
using namespace shapes;
Rectangle::Rectangle(int X0, int Y0, int X1, int Y1){
    x0 = X0;
    y0 = Y0;
    x1 = X1;
    y1 = Y1;
}
Rectangle::~Rectangle() {}
int Rectangle::getLength() {
    return (x1 - x0);
}
int Rectangle::getHeight() {
    return (y1 - y0);
} 
int Rectangle::getArea() {
    return (x1 - x0) * (y1 - y0);
}
void Rectangle::move(int dx, int dy) {
    x0 += dx;
    y0 += dy;
    x1 += dx;
    y1 += dy;
}

矩形.h

namespace shapes {
    class Rectangle {
    public:
    int x0, y0, x1, y1;
    Rectangle(int x0, int y0, int x1, int y1);
    ~Rectangle();
    int getLength();
    int getHeight();
    int getArea();
    void move(int dx, int dy);
    };
 }

矩形.pyx

# distutils: language = c++
# distutils: sources = Rectangle.cpp
cdef extern from "Rectangle.h" namespace "shapes":
    cdef cppclass Rectangle:
        Rectangle(int, int, int, int)
        int x0, y0, x1, y1
        int getLength()
        int getHeight()
        int getArea()
        void move(int, int)
cdef class PyRectangle:
    cdef Rectangle *thisptr
    def __cinit__(self, int x0, int y0, int x1, int y1):
        self.thisptr = new Rectangle(x0, y0, x1, y1)
    def __dealloc__(self):
        del self.thisptr
    def getLength(self):
        return self.thisptr.getLength()
    def getHeight(self):
        return self.thisptr.getHeight()
    def getArea(self):
        return self.thisptr.getArea()
    def move(self, dx, dy):
        self.thisptr.move(dx, dy)

setup.py

from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize(
       "rectangle.pyx",            # our Cython source
       sources=["Rectangle.cpp"],  # additional source file(s)
       language="c++",             # generate C++ code
      ))

不得不承认,我犯了同样的错误,首先在rectangle.pyx中缺少以下行。

# distutils: language = c++
# distutils: sources = Rectangle.cpp

通读了这里的帖子后,我意识到并修复了它。

但是,当我使用以下语句编译C++类时,

python rectangle.pyx

我有以下错误消息:

File "rectangle.pyx", line 4
    cdef extern from "Rectangle.h" namespace "shapes":
              ^
SyntaxError: invalid syntax

为什么会弹出此错误?我可以知道如何解决它吗?

非常感谢。:)

====

======================================================

PS:当我尝试运行setup.py时,我遇到了一个g++错误:

我跑了:

python setup.py build_ext

g++错误是

error: command 'g++' failed with exit status 1

根据@Bakuriu的建议,我发现以下程序有效:

假设您正在使用命令提示符

  1. CD 到包含.pyxsetup文件的目录。
  2. 使用 Cython 构建扩展,例如

    Cython -a rect.pyx --cplus

  3. 使用 Python 设置扩展,例如

    Python setup.py build_ext --inplace

使用扩展时,您可以:

  1. 将 .pyd 文件的目录追加到系统路径

    import sys

    sys.path.append("C:\yourDirectory")

  2. 根据需要使用扩展:)

    import Rectangle

    r = Rectangle.PyRectangle(1,2,3,4)