call python function from c++ (visual studio 2019)

1

I want to call the function from a python file from the visual studio 2019. By googling, it looks like I need to use the following function. I added a "Sample.py" in the same place where the exe is stored for the c++ .

int main()
{
    Py_Initialize();
    // Create some Python objects that will later be assigned values.

    PyObject* pName, * pModule, * pFunc, * pArgs = nullptr, * pValue; 
    pName = PyUnicode_FromString((char*)"Sample"); 
    pModule = PyImport_Import(pName); 
    pFunc = PyObject_GetAttrString(pModule, (char*)"fun"); 
    pValue = PyObject_CallObject(pFunc, pArgs);
}

In the "Sample.py" which is placed in the same path as the exe of the c++

import matplotlib.pyplot as plt

def fun(): x = [1,2,3]
y = [2,4,1]
plt.plot(1, 2)

And when i run the c++ code, it throws an exception at PyObject_CallObject(pFunc, pArgs); saying Exception thrown at 0x00007FFC54B6F3D2 (python37.dll) in ConsoleApplication9.exe: 0xC0000005: Access violation reading location 0x0000000000000008. Unhandled exception thrown: read access violation. v was nullptr.

I just want to know if im missing any thing in my visual studio setup

Because when i change the sample.py to just following without the #import, it works fine

def fun():  print("Hello from a function")
python
c++
asked on Stack Overflow May 24, 2021 by pdk5 • edited May 24, 2021 by pdk5

1 Answer

0

I changed the following and plotting is ok now !

#include <iostream>
#include "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\include\Python.h"

using namespace std;

int main(int)
{
    Py_Initialize();//-Initialize python interpreter
    if (!Py_IsInitialized())
    {
        PyRun_SimpleString("print 'inital error!' ");
        return -1;
    }
    //PyRun_SimpleString("print 'inital ok! ");
    PyRun_SimpleString("import sys");//--It is equivalent to the import sys statement in python, sys is to deal with the interpreter
    PyRun_SimpleString("sys.path.append('./')"); //Specify the directory where pytest.py is located
    PyRun_SimpleString("sys.argv = ['python.py']");
    PyObject* pName = NULL;
    PyObject* pMoudle = NULL;//---Store the python module to be called
    PyObject* pFunc = NULL;//---Store the function to be called
    pName = PyUnicode_FromString("Sample"); //Specify the file name to be imported
    pMoudle = PyImport_Import(pName);//--Using the import file function to import the helloWorld.py function
    if (pMoudle == NULL)
    {
        PyRun_SimpleString("print 'PyImport_Import error!' ");
        return -1;
    }
    pFunc = PyObject_GetAttrString(pMoudle, "fun");//--Find the hello function in the python reference module helloWorld.py
    PyObject_CallObject(pFunc, NULL);//---Call hello function

    Py_Finalize();//---Clean up the python environment and release resources
    return 0;
}

The plot script in Sample.py is:

import matplotlib.pyplot as plt
import numpy as np
def fun():
    x = np.arange(-5, 5, 0.02)
    y = np.sin(x)
    plt.axis([-np.pi, np.pi, -2, 2])
    plt.plot(x, y, color="r", linestyle="-", linewidth=1)
    plt.show()
answered on Stack Overflow May 25, 2021 by pdk5

User contributions licensed under CC BY-SA 3.0