在Windows的VSCode中调试Python C/ c++扩展



问题总结

我正在为Python开发一个自C扩展,以提高特定代码段的性能。我想调试这个扩展,但我还没有成功到目前为止。我已经遵循了几个链接,如Nadiah或Bark的链接,但我总是有同样的问题:我不能在C代码的任何断点处停止。

方法我已经试过了

这个想法是将Python作为主进程运行,并将编译后的C代码附加到这个主进程。下面我留下一个最小的可重复的例子:

Python文件

import os
import greet
pid = os.getpid()
test=2.2
greet.greet('World')
print("hi")

你可以看到,我甚至检索进程ID,以便在附加C代码时在vscode中选择这个ID,如下所示:

C代码

#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);
}

我用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)
],
)

我甚至指定O0选项有所有的调试符号。

启动JSON文件

"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"
}
]

我遵循的调试步骤

  1. 在python文件中添加一个断点,运行启动配置" python: Current file "并等待断点到达。
  2. 运行" (gdb) Attach "启动配置,选择路径包含"/.vscode/"的python解释器。在本例中,Windows中的,我没有得到提示输入我的用户密码,因为它发生在Linux中。
  3. 设置c++文件中的断点
  4. python调试器当前在断点处停止。从调试器"(gdb) Attach"切换回另一个调试器"Python: Current File"并按F5 (Continue)。

在最后一步中,vscode应该自动在python和c++代码之间的两个调试器之间跳转,但我无法实现此行为。

我能单独调试Python和C程序,但不能一起调试。

在Windows上调试Python c++代码时,您应该使用配置"(Windows)附件"在你的发布中。json文件。为了简化将c++调试器附加到python调试器上的过程,您可以使用VScode扩展名" python c++ Debug"。

来自Nidiah和Bark的两个例子都是基于Linux的。

在Windows上,您可以将C/c++代码编译成.dll文件(带有DEBUG信息),并在python中使用ctypes加载它。

Windows的限制:

GDB在Cygwin和MinGW上不能中断正在运行的进程。要在应用程序运行时(不是在调试器下停止)设置断点,或暂停正在调试的应用程序,请在应用程序终端按Ctrl-C

最新更新