[英]Debug Python/C++ program with bad_alloc
我有一个与 PyBind11 C++ 库接口的 Python 程序。
在图书馆的某个地方,有些东西正在抛出std::bad_alloc
。 Python 捕捉到这一点并轻松引发异常:
MemoryError: std::bad_alloc
在 GDB 中运行它:
gdb --ex run --args python3 ./my_program
在分配错误时不会导致中断。
如果我可以让 Python 对错误分配进行段错误或告诉 GDB 在 Python 之前捕获异常,我将能够调试它。 不幸的是,我也不知道该怎么做。
调试它需要几个步骤。 首先,我们需要调试符号。 PyBind11 剥离了这些,因此我们必须将它们取回。
我的 CMake 文件如下所示:
cmake_minimum_required(VERSION 3.10)
find_package(pybind11 REQUIRED)
pybind11_add_module(my_python_module my_python_module.cpp)
target_compile_features(my_python_module PUBLIC cxx_std_17)
要找回符号,我需要它看起来像这样:
cmake_minimum_required(VERSION 3.10)
find_package(pybind11 REQUIRED)
pybind11_add_module(my_python_module my_python_module.cpp)
target_compile_features(my_python_module PUBLIC cxx_std_17)
target_link_libraries(my_python_module PRIVATE pybind11::module)
add_library(restore_default_visibility INTERFACE)
target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)
target_link_libraries(my_python_module PRIVATE restore_default_visibility)
我还需要一个调试版本:
cmake -DCMAKE_BUILD_TYPE=Debug ..
现在,我可以启动我的 Python 程序:
gdb --args python3 ./my_program
一个 GDB 启动,我为std::bad_alloc
设置了一个断点:
catch throw std::bad_alloc
现在我可以通过输入c
来运行我的程序。
后来,当它崩溃时,我可以使用bt
命令获取回溯, up
和down
导航堆栈, print
显示变量的内容,以及Ctrl+X+A
来查看源代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.