CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Join Date
    May 2015
    Posts
    500

    Calling python from c++ in visual studio

    Hello,

    I used the visual studio installer to install python. I could run the basic python program.
    Now i want to make a c++ console program and call the python script from there.

    When googling i saw i need to include the "Python.h" in my c++ . But i donot find the Python.h file . Is it because i used visual studio to install the python. And most of googling have installed python separately.

    Please could you kindly help.

    thanks
    pdk

  2. #2
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Calling python from c++ in visual studio

    Sorry I can't help as I have never used python. However, doing a google search for the problem gave many items. Perhaps one of them might help?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    May 2015
    Posts
    500

    Re: Calling python from c++ in visual studio

    Thankyou very much kaud. I also have never used python . But it looked like charts are easy in python. so was exploring.

    I installed python via visual studio installer and I was hoping the visual studio takes care of integration. But it looks like i can just run either python or c++ separately.
    Googling gave that, i need to download the python.
    Will try that. Bit slow in IT

  4. #4
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Calling python from c++ in visual studio

    When you installed python, what install options did you choose? From VS Installer, what are the python installation details?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  5. #5
    Join Date
    May 2015
    Posts
    500

    Re: Calling python from c++ in visual studio

    Thankyou very much kaud.

    Now finally it works !!!
    I was using old VS. google told me to install later versions and we can download python with it. So I upgraded to VS2019, and ticked the python 2 for x64.

    With that option , it created a new directory, C:\Python27amd64\

    Now I created a new console application:
    Code:
    #include <iostream>
    #include "C:\Python27amd64\include\Python.h"
    
    int main()
    {
        Py_Initialize();
        PyRun_SimpleString("from time import time,ctime\n"
         "print('Today is',ctime(time()))\n");
        //std::cout << "Hello World!\n";
    }
    And also followed the following steps :
    1. Properties > C/C++ > General > Additional Include Directories. I added the "C:\Python27amd64\include"
    2.Properties > Linker > General > Additional Library Directories. : I added C:\Python27amd64\libs
    3.Properties > Linker > Input > Additional Dependencies: I added python27.lib
    4. I changed the build to "Release x64". Because it couldnot find the debug libraries

    thankyou
    Pdk
    Last edited by pdk5; May 23rd, 2021 at 10:24 AM.

  6. #6
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Calling python from c++ in visual studio

    Are you using python 3 or python 2? You say you ticked python 3 (3.7.8)- but then you refer to python 2 libs/include (2.7) ?? Shouldn't these refer to python 3 libs?

    AFAIK python 2 and python 3 are quite different.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    May 2015
    Posts
    500

    Re: Calling python from c++ in visual studio

    Sorry kaud, yes it was my mistake, i had changed to "Python 2"

  8. #8
    Join Date
    May 2015
    Posts
    500

    Re: Calling python from c++ in visual studio

    Actually , i want to call the function from a python file.
    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++
    Code:
        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;
    But I am getting the error at red line:

    0x201c: this character is not alloed as first characted of an identifier.

  9. #9
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Calling python from c++ in visual studio

    Note that you're not using " in the code. You're using non-ascii opening double quote and closing double quote.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  10. #10
    Join Date
    May 2015
    Posts
    500

    Re: Calling python from c++ in visual studio

    Thankyou very much kaud. Im sorry, im asking too many things. I was hoping to finish this today, but it looks like taking more time..


    Actually the issue is resolved when i changed to following
    Code:
    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:
    import matplotlib.pyplot as plt
    
    # 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()
    But the Sample.py the import in red doesnot work

  11. #11
    Join Date
    May 2015
    Posts
    500

    Re: Calling python from c++ in visual studio

    Just to update, I upgraded to python3 and above error is not seen
    Code:
    #include <iostream>
    #include "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\include\Python.h"
    
    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
    Code:
    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 "v was nullptr"

    Sample.py is put in the same exe as the c++ exe. Not sure if i need to do anything else ?
    Last edited by pdk5; May 24th, 2021 at 11:50 AM.

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

    Re: Calling python from c++ in visual studio

    According to the docs, PyUnicode_FromString expects the contents of the sample.py file, not just the "sample" string.

    So it seems you will need to open the sample.py file, read its contents as utf8 into a char* buffer, and pass the buffer to PyUnicode_FromString.

  13. #13
    Join Date
    May 2015
    Posts
    500

    Re: Calling python from c++ in visual studio

    Thanks a lot Arjay for the help.

    Actually when i changed the contents of Sample.py to:
    Code:
    import matplotlib.pyplot as plt
    
    def fun(): print("Hello from a function")
    This works ok !. It prints in the console.

    But somehow the plt.plot(x, y) does not work

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

    Re: Calling python from c++ in visual studio

    To debug, you need to separate the functioning of the python script from invoking the python script from C++. In other words, get the python script running properly by starting it from the command line. Does it work? Does it plot? Btw, not sure what the expected output is. Do you expect it to plot to the console window?

    At any rate, once it works in python only then move to attempting to launch it from c++.

  15. #15
    Join Date
    May 2015
    Posts
    500

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

    Thankyou very much. Your suggestion was very helpful indeed. Eventhough it is still not working, but is better now. The earlier error is gone.

    The script had to have some indent issues:
    Code:
    from matplotlib import pyplot as plt
    
    def fun():
        x = [5, 2, 9, 4, 7]
      
        # Y-axis values
        y = [10, 5, 8, 4, 2]
      
        # Function to plot
        plt.plot(x,y)
      
        # function to show the plot
        plt.show()
    Now on command line i did the following to call the function directly.
    C:\Users\pdk\source\repos\ConsoleApplication9\x64\Release>python -c "from Sample import fun; fun()"

    The chart was displayed ok !!!!


    Now when I ran from the c++, the earlier exception of read access violation is no longer there. But still the chart is not displaying. Difficult to debug this.
    Btw, i am running in release mode, as python library is release mode.

    Not sure how to proceed further
    Last edited by pdk5; May 25th, 2021 at 03:41 AM.

Page 1 of 2 12 LastLast

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
  •  





Click Here to Expand Forum to Full Width

Featured