我试图使用cython从python脚本调用c ++代码。我已经设法使用here中的示例,但问题是:我的c ++代码包含来自opencv的非标准库。我相信我没有正确链接它们所以我需要有人查看我的 setup.py 和我的 cpp_rect.h 和 cpp_rect.cpp 文件。
我得到的错误是关于* .cpp文件的粗线: cv :: Mat img1(7,7,CV_32FC2,Scalar(1,3)); 当我尝试测试库,我执行$ python userect.py
时收到包含错误:
Traceback (most recent call last):
File "userect.py", line 2, in <module>
from rectangle import Rectangle
ImportError: dlopen(/Users/marcelosalloum/Desktop/python_cpp_interface/rectangle.so, 2): Symbol not found: __ZN2cv3Mat10deallocateEv
Referenced from: /Users/marcelosalloum/Desktop/python_cpp_interface/rectangle.so
Expected in: flat namespace
in /Users/marcelosalloum/Desktop/python_cpp_interface/rectangle.so
未找到符号(__ZN2cv3Mat10deallocateEv)与cv::Mat::deallocate()
函数有关,这表示我的导入无法正常工作。
有什么想法吗?
我的其他课程如下:
这是我的 setup.py 文件。注意我已经包含了2个目录,但不确定我是否正确使用了:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'Demos',
ext_modules=[
Extension("rectangle",
sources=["rectangle.pyx", "cpp_rect.cpp"], # Note, you can link against a c++ library instead of including the source
include_dirs=[".", "/usr/local/include/opencv/", "/usr/local/include/"],
language="c++"),
],
cmdclass = {'build_ext': build_ext},
)
我的 cpp_rect.h 文件包含cv.h和命名空间cv,如下所示:
#include "source/AntiShake.h"
#include <iostream>
#include "cv.h"
using namespace cv;
class Rectangle {
public:
int x0, y0, x1, y1;
Rectangle();
Rectangle(int x0, int y0, int x1, int y1);
~Rectangle();
int getLength();
int getHeight();
int getArea();
void move(int dx, int dy);
**void openCV();**
Rectangle operator+(const Rectangle& other);
};
我的openCV()函数只是从opencv实例化一个cv :: Mat(文件 cpp_rect.cpp ):
#include "cpp_rect.h"
Rectangle::Rectangle() {
x0 = y0 = x1 = y1 = 0;
}
Rectangle::Rectangle(int a, int b, int c, int d) {
x0 = a;
y0 = b;
x1 = c;
y1 = d;
}
Rectangle::~Rectangle() {
}
void Rectangle::openCV(){
**cv::Mat img1(7,7,CV_32FC2,Scalar(1,3));**
}
...
我可以使用以下命令编译该文件:$ python setup.py build_ext --inplace
,它为我提供* .so文件。但是当我运行我的userect.py脚本时,我得到的问题包括首先在这个问题中描述的错误。
任何想法?
答案 0 :(得分:3)
感谢DietmarKühl的评论和this video from youtube!
出了什么问题?我发现我的setup.py配置错误。应该是这样的:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'DyCppInterface',
version = '1.0',
author = 'Marcelo Salloum dos Santos',
# The ext modules interface the cpp code with the python one:
ext_modules=[
Extension("rectangle",
sources=["rectangle.pyx", "cpp_rect.cpp"], # Note, you can link against a c++ library instead of including the source
include_dirs=[".","source" , "/opt/local/include/opencv", "/opt/local/include"],
language="c++",
library_dirs=['/opt/local/lib', 'source'],
libraries=['opencv_core', 'LibCppOpenCV'])
],
cmdclass = {'build_ext': build_ext},
)
为了正确配置它,需要注意的三件事是:
有关如何为cython配置库的更多问题可以通过观看this video on how to use and configure a dynamic library (using Eclipse CDT)来解答。