无法执行Cython包装的Python代码 [英] Unable to execute Cython wrapped Python code
问题描述
我正在使用Cython导出python代码的C ++ API.该应用程序将在Ubuntu上执行.项目文件位于此处
I am exporting C++ API for python code using Cython. The application will be executed on Ubuntu. The project files are present here
我正在包装的函数,读取图像的文件名并显示图像. Show_Img.pyx
文件如下所示
The function I am wrapping, reads the file name of the image and displays the image. The Show_Img.pyx
file looks as follows
import cv2
cdef public void Print_image(char* name):
img = cv2.imread(name)
cv2.imshow("Image", img)
while(True):
if cv2.waitKey(1) & 0xFF == ord('q'):
break
从Cython生成的c ++接口如下所示
The c++ interface generated from Cython looks as follows
__PYX_EXTERN_C DL_IMPORT(void) Print_image(char *);
头文件包含在我的algo.cpp
中,该文件调用如下函数
The header file is included in my algo.cpp
, which calls the function like below
#include<iostream>
#include<Python.h>
#include"Show_Img.h"
using namespace std;
int main(){
char *name = "face.jpg";
Py_Initialize();
Print_image(name);
Py_Finalize();
return 0;
}
使用下面的命令,我还可以编译上面的代码并生成应用程序
With the command below, I can also compile the above code and also generate the application
g++ algo.cpp `pkg-config --libs --cflags python-2.7` `pkg-config --libs --cflags opencv` -L. -lShow_Img -o algo
还正确设置了库LD_LIBRARY_PATH
的路径
应用程序执行后,出现错误Segmentation fault (core dumped)
Upon execution of the application, there is an error Segmentation fault (core dumped)
为什么我无法执行该应用程序,生成过程中是否有错误?或图书馆链接?
Why am I unable to execute the application, is there a mistake in the generation process? or Library linking?
推荐答案
要继续我的评论,您必须为该模块调用init
函数:
To follow up on my comment, You have to call an init
function for the module:
// ...
Py_Initialize();
initShow_Img(); // for Python3
// (especially with the more modern 2 phase module initialization)
// the process is a little more complicated - see the documentation
Print_image(name);
Py_Finalize();
// ...
原因是这样设置模块,包括执行行import cv2
.没有它,诸如访问模块全局变量(进入cv2
)之类的东西将无法可靠地工作.这可能是分割错误的原因.
The reason being is that this sets up the module, include executing the line import cv2
. Without it things like accessing the module globals (to get to cv2
) won't reliably work. This a likely cause of the segmentation fault.
这在文档示例.
这篇关于无法执行Cython包装的Python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!