如何在 Visual Studio 2015 中调试从C++项目调用的 Python 代码



我有一个Visual Studio 2015 c ++项目,它调用了一个python模块。

以下关于微软网站的教程提供了一种在从Visual Studio python项目调用C++代码时调试代码的方法。

编号 : https://learn.microsoft.com/en-us/visualstudio/python/debugging-mixed-mode

同样,是否可以调试由C++程序调用的Python代码

例如我的C++代码如下

#include "stdafx.h"
#include <iostream>
#ifdef _DEBUG
#undef _DEBUG
#include <python.h>
#define _DEBUG
#else
#include <python.h>
#endif
int _tmain(int argc, _TCHAR* argv[])
{
printf("Calling Python to find the sum of 2 and 2.n");
// Initialize the Python interpreter.
Py_Initialize();
// Create some Python objects that will later be assigned values.
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
// Convert the file name to a Python string.
pName = PyUnicode_FromString("sample");
// Import the file as a Python module.
pModule = PyImport_Import(pName);
// Create a dictionary for the contents of the module.
pDict = PyModule_GetDict(pModule);
// Get the add method from the dictionary.
pFunc = PyDict_GetItemString(pDict, "add");
// Create a Python tuple to hold the arguments to the method.
pArgs = PyTuple_New(2);
// Convert 2 to a Python integer.
pValue = PyLong_FromLong(2);
// Set the Python int as the first and second arguments to the method.
PyTuple_SetItem(pArgs, 0, pValue);
PyTuple_SetItem(pArgs, 1, pValue);
// Call the function with the arguments.
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
// Print a message if calling the method failed.
if (pResult == NULL)
printf("Calling the add method failed.n");
// Convert the result to a long from a Python object.
long result = PyLong_AsLong(pResult);
// Destroy the Python interpreter.
Py_Finalize();
// Print the result.
printf("The result is %d.n", result); std::cin.ignore(); return 0;
}

调用 Python 3 代码,如下所示

# Returns the sum of two numbers.
def add(a, b):
c = a + b
return c

调试时,我想在python代码中放置一个断点

,以下指令
c = a + b

因此,在我按 F11 到达C++代码中的以下指令后,Visual Studio 应该深入研究 Python 代码

PyObject* pResult = PyObject_CallObject(pFunc, pArgs);

答案在 https://learn.microsoft.com/en-us/visualstudio/python/debugging-mixed-mode 作为注释提供,其中指出

此处所述的混合模式调试仅在将 Python 项目加载到 Visual Studio 中时启用。该项目确定 Visual Studio 的调试模式,这就是使混合模式选项可用的原因。但是,如果加载了一个C++项目(就像在另一个应用程序中嵌入 Python 时一样,如 python.org 中所述),则 Visual Studio 将使用不支持混合模式调试的本机C++调试器。

在这种情况下,请在不调试的情况下启动C++项目("调试">"启动而不调试"或按 Ctrl+F5),然后使用"调试">"附加到进程..."。在出现的对话框中,选择相应的进程,然后使用"选择...按钮打开"选择代码类型"对话框,您可以在其中选择 Python,如下所示。选择"确定"关闭该对话框,然后选择"附加"以启动调试器。请注意,可能需要在 C++ 应用中引入适当的暂停或延迟,以确保它不会调用要调试的 Python,然后才能附加调试器。

最新更新