Unable to execute Cython wrapped Python code

。_饼干妹妹 提交于 2019-12-19 21:46:45

问题


I am exporting C++ API for python code using Cython. The application will be executed on Ubuntu. The project files are present here

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

The c++ interface generated from Cython looks as follows

__PYX_EXTERN_C DL_IMPORT(void) Print_image(char *);

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

also the path to the library LD_LIBRARY_PATH is set correctly

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?


回答1:


To follow up on my comment, You have to call an init function for the module:

// ...
Py_Initialize();
initShow_Img(); // for Python3 use PyInit_Show_Img instead
Print_image(name);
Py_Finalize();
// ...

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.

This is in the documentation example.



来源:https://stackoverflow.com/questions/42301919/unable-to-execute-cython-wrapped-python-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!