Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyImport_Import fails - Returns NULL

Tags:

c++

python

c

First off, yes I have seen this and this, however they didn't resolve my problem/error.


So, I'm trying to call a Python function from C/C++, but when PyImport_Import() is called it returns NULL.

Code:

PyObject* fname = PyBytes_FromString("hello");
PyObject* module = PyImport_Import(fname);

Where hello is my hello.py file in the same directory as the executable. I have no idea where my error is, could some please point me to it?

like image 422
Rakete1111 Avatar asked Dec 01 '22 15:12

Rakete1111


2 Answers

Without knowing a whole bunch of information about how your system is set up and the contents of the Python files involved, it's difficult to diagnose your problem. Far better to let the Python runtime tell you what is wrong.

The documentation states

PyObject* PyImport_ImportModule(const char *name)

...

Return a new reference to the imported module, or NULL with an exception set on failure

(emphasis mine)

The exception handling documentation states that you can call PyErr_Print() to print the current exception to stderr.

So to put this into practice:

PyObject* fname = PyBytes_FromString("hello");
PyObject* module = PyImport_Import(fname);
if (module == nullptr)
{
    PyErr_Print();
    std::exit(1);
}

This will at least get you started on figuring out the error.

For future convenience, you probably want to create your own C++ exception class to wrap Python errors (and to avoid peppering your code with things like calls to exit).

like image 93
wakjah Avatar answered Dec 09 '22 21:12

wakjah


I thought that PyBytes_FromString was the the 3.x alternative of PyString_From.

I was wrong. PyUnicode_FromString is the correct alternative.

(Thanks to @wakjah for given me the tip of using error handling)

like image 34
Rakete1111 Avatar answered Dec 09 '22 21:12

Rakete1111