running c++ code from python

2019-03-20 03:11发布

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 parse these arguments from a python scripts parsearguments.py

So for example:

def parse_arguments:
  ...# some code
  return arguments

Now, how do i communicate between python and c++. I have been reading and see that cython, boost python are the options but I have a hard time finding the right simple hello world example.

Any suggestions will be appreciated. Thanks

4条回答
Evening l夕情丶
2楼-- · 2019-03-20 03:29

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.

查看更多
ら.Afraid
3楼-- · 2019-03-20 03:33

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.

查看更多
虎瘦雄心在
4楼-- · 2019-03-20 03:41

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.

查看更多
放我归山
5楼-- · 2019-03-20 03:43

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.

查看更多
登录 后发表回答