I have a visual studio 2015 c++ project which calls a python module.
The following tutorial on microsoft website give a method to debug C++ code when it is called from a visual studio python project.
ref : https://learn.microsoft.com/en-us/visualstudio/python/debugging-mixed-mode
similarly is it possible to debug a python code which is being called by a C++ program
For example my C++ code is as follows
#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;
}
which calls a Python 3 code as follows
# Returns the sum of two numbers.
def add(a, b):
c = a + b
return c
While debugging I want to put a break-point a the following instruction in the python code
c = a + b
so after I press F11 on reaching to the following instruction in the C++ code, visual studio should dive in the python code
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);