0

I m using Ubuntu 20.04, python 3.8 and developing a C++ project in Qt Creator. I m trying to call a python file from C++ code. I have created an environment in conda and calling the py file. There is segmentation fault occurring when I m attempting to import cv2 module. Other modules like sys, numpy can be imported. cv2 is installed in the environment and can be accessed when I run python from cmd prompt.

Also I tried to run the python commands directly in a C++ file, like:

PyRun_SimpleString("import cv2");

But this also sends segmentation fault. I tried giving path of the site-packages directory in CMakeLists.txt but it also resulted in same error.

mainwindow.cpp:

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <stdio.h>
#include <pyhelper.hpp>
#include <string>
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    Py_InitializeEx(0);

    PyRun_SimpleString("import cv2");

}

MainWindow::~MainWindow()
{
    delete ui;
}

Qt Creator debugger stack trace is as below: enter image description here enter image description here

surajj4837
  • 49
  • 1
  • 10
  • Is there any dynamic linking in this processs? try using [PyImport_ImportModule](https://docs.python.org/3/c-api/import.html#c.PyImport_ImportModule) and to print the error with [PyErr_Print](https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Print). also, check that PYTHONPATH is directed to this module location – jsofri Nov 15 '21 at 06:20
  • Attach the debugger and show us a stack trace please. You may need to install the python debugging symbols – Botje Nov 15 '21 at 10:20
  • @jsofri I tried importing the module `PyObject * test = PyImport_ImportModule("cv2");` but this statement gives segmentation fault. I have added directory path of cv2 module to PYTHONPATH. – surajj4837 Nov 15 '21 at 11:12

0 Answers0