我在Cython中包装了一个C ++库,我想将其作为Python包分发。我一直在使用本教程作为指南。
这是事物的组织方式。
.
├── inc
│ └── Rectangle.h
├── rect
│ ├── __init__.py
│ └── wrapper.pyx
├── setup.py
└── src
└── Rectangle.cpp
我已将这些文件的内容粘贴在文章的底部以及此GitHub存储库中。
我使用进行编译和安装时没有问题python setup.py install
,并且可以import rect
从解释器中毫无问题地进行操作。但这似乎是一个空类:我不能Rectangle
使用以下任何一个来创建对象。- Rectangle
- rect.Rectangle
- wrapper.Rectangle
-rect.wrapper.Rectangle
我在这里做错了什么?
Rectangle.h
教程中的内容,复制和粘贴。
namespace shapes {
class Rectangle {
public:
int x0, y0, x1, y1;
Rectangle();
Rectangle(int x0, int y0, int x1, int y1);
~Rectangle();
int getArea();
void getSize(int* width, int* height);
void move(int dx, int dy);
};
}
的内容Rectangle.cpp
。
#include "Rectangle.h"
namespace shapes {
Rectangle::Rectangle() { }
Rectangle::Rectangle(int X0, int Y0, int X1, int Y1) {
x0 = X0;
y0 = Y0;
x1 = X1;
y1 = Y1;
}
Rectangle::~Rectangle() { }
int Rectangle::getArea() {
return (x1 - x0) * (y1 - y0);
}
void Rectangle::getSize(int *width, int *height) {
(*width) = x1 - x0;
(*height) = y1 - y0;
}
void Rectangle::move(int dx, int dy) {
x0 += dx;
y0 += dy;
x1 += dx;
y1 += dy;
}
}
Cython包装器代码wrapper.pyx
。
# distutils: language = c++
# distutils: sources = src/Rectangle.cpp
cdef extern from "Rectangle.h" namespace "shapes":
cdef cppclass Rectangle:
Rectangle() except +
Rectangle(int, int, int, int) except +
int x0, y0, x1, y1
int getArea()
void getSize(int* width, int* height)
void move(int, int)
cdef class PyRectangle:
cdef Rectangle c_rect # hold a C++ instance which we're wrapping
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)
setup.py
我已为此文件组织改编的脚本。
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(
name='rect',
packages=['rect'],
ext_modules=cythonize(Extension(
'Rectangle',
sources=['rect/wrapper.pyx', 'src/Rectangle.cpp'],
include_dirs=['inc/'],
language='c++',
extra_compile_args=['--std=c++11'],
extra_link_args=['--std=c++11']
)),
)
在这种情况下,问题出在该.pyx
文件和扩展名没有相同的基名。当我改名wrapper.pyx
到Rectangle
并重新安装,我能够运行Python解释如下。
>>> import Rectangle
>>> r = Rectangle.PyRectangle(0, 0, 1, 1)
>>> r.get_area()
1
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句