Calling a Python function in Visual C++ - Access violation exception is thrown

-1

I was trying to call a very basic python function in Visual C++ (Visual Studio 2017: x64 - Release, Python 2.7) by following this link: https://www.coveros.com/calling-python-code-from-c/

I configured the libraries and includes and the code runs with no syntax errors, however an access-violation exception is thrown at this line: PyObject* pResult = PyObject_CallObject(pFunc, pArgs);

Exception thrown at 0x0000000063D351F9 (python27.dll) in PyCPP.exe: 0xC0000005: Access violation reading location 0x0000000000000008. The program '[17468] PyCPP.exe' has exited with code 0 (0x0).

Can somebody please point out the error in this program. I really appreciate it.

Here are the C++ and Python codes:

#include "pch.h"
#include <iostream>
#include <Python.h>

int main()  
{
    printf("Calling Python to find the sum of 2 and 2.\n");
    // Initialize the Python interpreter.
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");
    // 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 = PyString_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 = PyInt_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 = PyInt_AsLong(pResult);
    // Destroy the Python interpreter.
    Py_Finalize();
    // Print the result.
    printf("The result is %d.\n", result); 
    std::cin.ignore(); 
    return 0;
}

Python code:

def add(a, b):
    return a+b
python
c++
visual-studio
64bit
pyobject
asked on Stack Overflow Apr 6, 2019 by user3112666

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0