用Cython包C++类,得到基本的例子

2024-04-27 01:05:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想学习如何用cython包装c++代码。为了做到这一点,我从cython网页上的基本c++示例开始,可以在这里找到:http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html

这看起来很简单,但我不能让它发挥作用。以下是我所做的:

矩形。h和矩形.cpp直接从网页复制

矩形。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);
};
}

在矩形.cpp在

^{pr2}$

然后创建一个.pyx文件,名为“矩形pyx“我把下面的代码放在这里:

cdef extern from "Rectangle.h" namespace "shapes":
    cdef cppclass Rectangle:
        Rectangle(int, int, int, int) except +
        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)

最后,一个“设置.py“”文件:

from distutils.core import setup
from Cython.Build import cythonize

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

我尝试在ubuntu和mac osx的终端上运行以下命令来构建代码(我在两个操作系统上得到的结果相同):

python3 setup.py build_ext --inplace

这看起来编译得很好,文件夹中会出现一个新的.cpp文件和一个.so文件,但是当我启动python并尝试导入类时,我收到以下错误消息:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /home/codeFolder/rect.cpython-34m.so: undefined symbol: _ZN6shapes9Rectangle9getLengthEv

怎么了?在


Tags: selfmovedefcppintx1矩形y1
1条回答
网友
1楼 · 发布于 2024-04-27 01:05:11

看看你的设置.py以及您使用的链接中的片段:

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules = cythonize(Extension(
           "rect",                                # the extesion name
           sources=["rect.pyx", "Rectangle.cpp"], # the Cython source and
                                                  # additional C++ source files
           language="c++",                        # generate and compile C++ code
      )))

基本上,您错过了对Extension的调用(在Extension和/或cythoniza文档中有更多详细信息;)

相关问题 更多 >