Python Forum

Full Version: Calling python from c++ in visual studio
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

Im trying to call a Python function "fun"in the Sample.py from the c++ console program in visual studio 2019.
The Sample.py works for small one line print function.


But want to use the matplotlib, in the Sample.py file.
I tried the following, but it doesnot work.

Please kindly help. (being newbie to python)

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);

}
Sample.py was simple function to print.

But now I want to add the following to sample.py
Code:
view sourceprint?
import matplotlib.pyplot as plt

def fun():
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
  
# plotting the points 
plt.plot(x, y)
  
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
  
# giving a title to my graph
plt.title('My first graph!')
  
# function to show the plot
plt.show()