running c++ code from python

前端 未结 4 600
日久生厌
日久生厌 2021-02-06 05:39

I want to execute a code helloword.cpp which takes in some argument from console parses those arguments and then prints \"hello world\" in the console.

Now, I want to pa

相关标签:
4条回答
  • 2021-02-06 06:08

    To execute C++ code in python, you could effectively use boost python, here is a tutorial: http://www.boost.org/doc/libs/1_59_0/libs/python/doc/index.html You write a kind of wrapper outside you C++ code.

    If it is C code, python has internal library called ctypes.

    In both case, you should compile the C/C++ code into shared library.

    0 讨论(0)
  • 2021-02-06 06:20

    How about passing whatever text you generate with Python into the standard input of your C++ program? Basically, you have to use Python's subprocess module to fire up the C++ program and dump the text into its standard output.

    In case that your C++ program is required to be running separately in the background, you could try another form of interprocess communication, like unix domain sockets.

    Using boost::python is also an option, but it might be a little more difficult to deal with.

    0 讨论(0)
  • 2021-02-06 06:25

    A couple of other options besides Boost.python are SIP and SWIG (Simplified Wrapper and Interface Generator). Like Boost, SIP and SWIG are open source.

    SWIG is particularly powerful, but also a bit hairy. It provides support for interfacing C and C++ with a boatload of other languages including (not a complete list) Python, Perl, Lua, Tcl/Tk, Ocaml, Ruby, Java. One aspect of SWIG is that it parses your C++ headers. This has benefits and pitfalls. A benefit is that it does most of the work of generating the interfaces. A downside is that it doesn't handle some of the dark corners of C++ 2003, and it hasn't stepped up to C++11 at all. Another downside is that compilation of a large project becomes slow. Very, very slow.

    0 讨论(0)
  • 2021-02-06 06:28

    Using boost.python sounds like a good solution for me. But depending on your C++ experience this can be quite tricky. A good point to start is here:

    http://wiki.python.org/moin/boost.python

    Boost.Python enables you to export C++ classes and member functions to Python to be able to use them from there.

    0 讨论(0)
提交回复
热议问题