[英]Syntax Error in Cython Example
我正在嘗試在此頁面上構建Cython示例。
我知道我的帖子與另一個問題非常相似。 但是,我生成了完全不同的錯誤消息。
這是我的代碼:
矩形文件
#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;
}
矩形
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的建議,我發現以下過程有效:
假設您正在使用命令提示符
.pyx
和setup
文件的目錄。 使用Cython構建擴展名,例如
Cython -a rect.pyx --cplus
使用Python設置擴展名,例如
Python setup.py build_ext --inplace
使用擴展程序時,您可以:
將.pyd文件目錄追加到系統路徑
import sys
sys.path.append("C:\\\\yourDirectory")
根據需要使用擴展名:)
import Rectangle
r = Rectangle.PyRectangle(1,2,3,4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.