Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug a Python C/C++ extension in VSCode on Windows

Summary of the problem

I am developing a self C extension for Python in order to improve the performance of a specific piece of code. I would like to debug this extension, but I have not succeeded so far. I have followed several links such as this from Nadiah or this from Bark, but I always have the same problem: I cannot stop at any breakpoint of the C code.

Approach I have tried

The idea is to run Python as the main process and attach the compiled C code to this main process. Following I leave a minimal reproducible example:

Python file

import os
import greet

pid = os.getpid()

test=2.2

greet.greet('World')

print("hi")

As you can see, I even retrieve the process ID in order to pick this ID in vscode when attaching the C code, which is as follows:

C code

#include <Python.h>

static PyObject *
greet_name(PyObject *self, PyObject *args)
{
    const char *name;

    if (!PyArg_ParseTuple(args, "s", &name))
    {
        return NULL;
    }
    
    printf("Helllo %s!\n", name);

    Py_RETURN_NONE;
}

static PyMethodDef GreetMethods[] = {
    {"greet", greet_name, METH_VARARGS, "Greet an entity."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef greet =
{
    PyModuleDef_HEAD_INIT,
    "greet",     /* name of module */
    "",          /* module documentation, may be NULL */
    -1,          /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
    GreetMethods
};

PyMODINIT_FUNC PyInit_greet(void)
{
    return PyModule_Create(&greet);
}

I compile the C code with GCC 8.1 by running python setup.py install:

Setup file

import os

from setuptools import setup, Extension

os.environ["CC"] = "g++-8.1.0"

_DEBUG = True
_DEBUG_LEVEL = 0
# extra_compile_args = sysconfig.get_config_var('CFLAGS').split()
extra_compile_args = ["-Wall", "-Wextra"]
if _DEBUG:
    extra_compile_args += ["-g3", "-O0", "-DDEBUG=%s" % _DEBUG_LEVEL, "-UNDEBUG"]
else:
    extra_compile_args += ["-DNDEBUG", "-O3"]

setup(
    name='greet',
    version='1.0',
    description='Python Package with Hello World C Extension',
    ext_modules=[
        Extension(
            'greet',
            sources=['greetmodule.c'],
            py_limited_api=True,
            extra_compile_args=extra_compile_args)
    ],
)

I even specify O0 option to have all debug symbols.

Launch JSON file

"configurations": [
    {
        "name": "(gdb) Attach",
        "type": "cppdbg",
        "request": "attach",
        "program": "venv/Scripts/python",
        "processId": "${command:pickProcess}",
        "MIMode": "gdb",
        // "miDebuggerPath": "/path/to/gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ]
    },
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal"
    }
]

Debug steps I follow

  1. Add a breakpoint in the python file, run the launch configuration “Python: Current File” and wait until the breakpoint is reached.
  2. Run the “(gdb) Attach” launch configuration, select the python interpreter whose path contains “/.vscode/”. In this case, in Windows, I am not getting prompted to enter my user password as it happens in Linux.
  3. Set breakpoints in the C++ Files
  4. The python debugger is currently stopped at a break point. Switch back from the debugger “(gdb) Attach” to the other debugger “Python: Current File” and press F5 (Continue).

In this last step, vscode should automatically jump between the two debuggers between python and c++ code, but I cannot achieve this behavior.

I am able to debug Python and C programs alone, but not together.

like image 911
David Duran Avatar asked Feb 06 '21 13:02

David Duran


People also ask

How do I debug a Python file in VS Code?

If you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File in Terminal.

How do I debug a VS Code extension?

You can easily run your extension under the debugger by pressing F5 . This opens a new VS Code window with your extension loaded. Output from your extension shows up in the Debug Console . You can set break points, step through your code, and inspect variables either in the Debug view or the Debug Console .

How do you debug C code in Visual code?

vscode folder. VSCode can create and auto-configure these files if we try to debug for the first time. To do that, open C++ file in VSCode and either hit F5 or go to Debug -> Start Debugging and select C++ (GDB/LLDB) then select g++.exe build and debug active file .


Video Answer


1 Answers

When debugging a Python C++ code on Windows you should use the configuration "(Windows) Attach" in your launch.json file. For simplifying the process of attaching the C++ debugger to the python debugger you can use the VScode extension "Python C++ Debug".

Both examples from Nidiah and Bark are based on Linux.

On Windows, you can compile your C/C++ code to a .dll file (with DEBUG info) and load it with ctypes in python.

like image 162
BeniBenj Avatar answered Oct 28 '22 19:10

BeniBenj