0

I'm getting a nullptr error trying to use the Python/C++ API. Most of these errors come in rather long/complicated code where someone tries to reference a pointer without setting it to something first, but I'm able to duplicate my behavior on just a few lines of code, and I have no idea what's going on.

Here's the MWE:

#include <Python.h>
#include <iostream>

int main()
{
    std::cout << "Hello World!\n\n";
    PyObject *pyl;
    pyl = PyLong_FromLong(3);
    std::cout << PyLong_AsLong(pyl) << std::endl;
}

I'm compiling this as a C++ console app in Visual Studio Community 2017. My Python version is 3.8.5. I'm building with Debugging in Release mode and x64 mode (my Python install is x64). I've done the following in the Configuration Properties:

  1. Added the directory containing python.lib and python38.lib to VC++ Directories → Library Directories;
  2. Added the directory containing Python.h to C/C++ → General → Additional Include Directories;
  3. Added the directory containing python.dll and python38.dll to the system PATH variable.

The error comes in the last line, and says:

Exception thrown: read access violation.
obj->ob_type was nullptr.

The call stack looks like this:

enter image description here

If I try something different, e.g. I assign pyl = PyList_New(3);, I get a slightly different error, Exception thrown: read access violation. _PyRuntime.gc.generation0 was nullptr.

I have to imagine maybe my Python install is messed up, or maybe I'm missing something really obvious, but I haven't seen an error like this anywhere else, so any ideas you folks might have would be greatly appreciated.

Note: the Python documentation says to include the definition #define PY_SSIZE_T_CLEAN in the code. This doesn't change what I see.

Further edit: Adding a call to Py_Initialize() directly after the Hello World print gives me this printout:

  • What happens if you add a call to the [Py_Initialize](https://docs.python.org/3/c-api/init.html#c.Py_Initialize) function? – kakkoko May 17 '21 at 01:30
  • @kakkoko Oh, good call, I tried that previously and should've put it in. I've edited the question to show what happens. – flevinBombastus May 17 '21 at 02:19
  • 1
    Your case is referred to as A in the answer. You need to help the interpreter to find the installation. – ead May 17 '21 at 02:50
  • 1
    See also related: https://stackoverflow.com/q/62390978/5769463 – ead May 17 '21 at 02:52

0 Answers0