First off, yes I have seen this and this, however they didn't resolve my problem/error.
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?
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
).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With