CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 20 of 20

Thread: Calling python from c++ in visual studio

  1. #16
    Join Date
    May 2015
    Posts
    450

    Re: Calling python from c++ in visual studio

    One more good news

    Code:
    #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;
    }
    Sample.py

    Code:
    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()
    I changed the function with one of the google suggestions and it finally works !!!

    Thanks a lot Arjay for your inputs helped me

  2. #17
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,488

    Re: Calling python from c++ in visual studio

    Good to hear you got it figured out. Btw, iirc you can still debug your code even when using release library dlls - you just can't step into the library code.

  3. #18
    Join Date
    May 2015
    Posts
    450

    Re: Calling python from c++ in visual studio

    Thanks Arjay, yes I remember i had to debug one module in our project sometime back due to historical reasons. It can still be debugged, except some variables maynot be visible being optimised.

    Now, my next step is to pass the vector from c++

    Also try to see if this can somehow integrated to MFC window !!!, rather than console

  4. #19
    Join Date
    May 2015
    Posts
    450

    Re: Calling python from c++ in visual studio

    Hello,
    First of all thanks a lot for this forum, for helping me . Very helpful and much appreciated.

    Just to keep my progress updated, now I can pass the array from c++ to python and plot.

    Code:
    #include <iostream>
    #include "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\include\Python.h"
    #include "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Lib\site-packages\numpy\core\include\numpy\arrayobject.h"
    #include <vector>
    using namespace std;
    
    int main(int)
    {
    
        Py_Initialize();//-Initialize python interpreter
        if (!Py_IsInitialized())
        {
            PyRun_SimpleString("print 'inital error!' ");
            return -1;
        }
        import_array();
        //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']");
    
        int fArray1[5] = { 5, 2, 9, 4, 7 };
        npy_intp m[1] = { 5 };// Initialize the Python Interpreter
    
        PyObject* c1 = PyArray_SimpleNewFromData(1, m, NPY_INT, fArray1);
    
        int fArray2[5] = { 10, 5, 8, 4, 2 };
        PyObject* c2 = PyArray_SimpleNewFromData(1, m, NPY_INT, fArray2);
    
        // Create Tupe of size 2 to pass two arguements
        PyObject* pArgs = PyTuple_New(2);
        PyTuple_SetItem(pArgs, 0, c1);
        PyTuple_SetItem(pArgs, 1, c2);
    
        PyObject* pName = NULL;
        PyObject* pMoudle = NULL;//---Store the python module to be called
        PyObject* pFunc = NULL;//---Store the function to be called
        PyObject* pArgTuple = NULL;
        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, pArgs);//---Call hello function
    
        Py_Finalize();//---Clean up the python environment and release resources
        return 0;
    }
    And python script to take this array input and plot :

    Code:
    import matplotlib.pyplot as plt
    import numpy as np
    def fun(x,y):
    
        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()

  5. #20
    Join Date
    Jun 2021
    Posts
    10

    Post Re: Calling python from c++ in visual studio

    You can now substitute the contents of your C++ source file with the following source code example:

    Code:
    #include “stdafx.h”
    
    #include <iostream>
    
    #include <Python.h>
    
    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 = 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; }

Page 2 of 2 FirstFirst 12

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)