在尝试Cython C++示例时未定义的符号导入恐怖

2024-10-02 18:19:39 发布

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

编辑:

我在macbook上尝试过同样的代码,效果很好。因此,问题仅限于我的linuxmint17.2系统,该系统使用anacondapython2.7、cython0.23.4和gcc4.8。macbook使用的是AnacondaPython2.7、Cython0.22.1和AppleLLVM版本6.1.0。在

原职务:

我试图让cythonc++示例从这里开始工作:http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html

由于有一些解释空间,我的确切代码粘贴在下面。它们都在一个目录中,cpp_example。在cpp_example目录中,我使用以下命令进行编译:

>python setup.py build_ext --inplace

编译将打印以下输出:

^{pr2}$

然后我试着跑:

>python main.py

我得到一个错误:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import rect
ImportError: /home/jason/projects/martian/workspaces/workspace1/cpp_example/rect.so: undefined symbol: _ZN6shapes9Rectangle9getLengthEv

未定义的符号看起来像是rectanglec++类的getLength方法的损坏版本。我不确定是我做错了什么,还是我的系统设置方式有问题。任何关于可能出问题的建议都将不胜感激。在

代码

在矩形.cpp公司名称:

#include "Rectangle.h"

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: sources = Rectangle.cpp
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      # hold a C++ instance which we're wrapping
    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
           language="c++",             # generate C++ code
      ))

在主.py公司名称:

import rect
print rect.PyRectangle(1,1,2,2)

Tags: pyselfreturndefcppintx1dy