Dav*_*ran 12 c c++ python debugging visual-studio-code
我正在为 Python 开发一个自 C 扩展,以提高特定代码段的性能。我想调试这个扩展,但到目前为止我还没有成功。我遵循了几个链接,例如来自 Nadiah或来自 Bark,但我总是遇到同样的问题:我无法在 C 代码的任何断点处停止。
这个想法是将 Python 作为主进程运行,并将编译后的 C 代码附加到这个主进程。下面我留下一个最小的可重复示例:
import os
import greet
pid = os.getpid()
test=2.2
greet.greet('World')
print("hi")
Run Code Online (Sandbox Code Playgroud)
如您所见,我什至在附加C代码时检索进程ID,以便在vscode中选择此ID,如下所示:
#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);
}
Run Code Online (Sandbox Code Playgroud)
我通过运行使用 GCC 8.1 编译 C 代码python setup.py install:
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)
],
)
Run Code Online (Sandbox Code Playgroud)
我什至指定O0选项来拥有所有调试符号。
"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"
}
]
Run Code Online (Sandbox Code Playgroud)
在这最后一步中,vscode 应该自动在 python 和 c++ 代码之间的两个调试器之间跳转,但我无法实现这种行为。
我可以单独调试 Python 和 C 程序,但不能一起调试。
Windows 的限制:
Cygwin 和 MinGW 上的 GDB 无法中断正在运行的进程。要在应用程序运行时(不在调试器下停止)设置断点,或暂停正在调试的应用程序,请按Ctrl-C应用程序终端中的 。