I want to know how can I create a python script that run c++ code.
I did find some talks about subprocess module but it's used to run commands I did find some talks about Boost and Swig but I didn't understand as a beginner how to use them
Testing subprocess:
import subprocess
subprocess.call(["g++", "main.cpp"],shell = True)
tmp=subprocess.call("main.cpp",shell = True)
print("printing result")
print(tmp)
Can any one help me please!
A simple example would be to create a .cpp
file:
// cpy.cpp
#include <iostream>
int main()
{
std::cout << "Hello World! from C++" << std::endl;
return 0;
}
And a Python script:
// cpy.py
import subprocess
cmd = "cpy.cpp"
subprocess.call(["g++", cmd])
subprocess.call("./a.out")
Then in the terminal, run the Python script:
~ python cpy.py
~ Hello World! from C++
EDIT:
If you want control of calling C++ functions from Python, you will need to create bindings to extend Python with C++. This can be done a number of ways, the Python docs has a thorough raw implementation of how it can be done for simple cases, but also there are libraries such as pybind and boost.Python that can do this for you.
An example with boost.Python:
// boost-example.cpp
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int printHello()
{
std::cout << "Hello, World! from C++" << std::endl;
}
BOOST_PYTHON_MODULE(hello)
{
def("print_hello", printHello);
}
You will need to create a shared object file (.so) and make sure to link the appropriate Python headers and libraries. An example might look like:
g++ printHello.cpp -fPIC -shared -L/usr/lib/python2.7/config-3.7m-x86_64-linux-gnu/ -I/usr/include/python2.7 -lpython2.7 -lboost_python -o hello.so
And in the same directory that you created the hello.so
file:
python
>>> import hello
>>> hello.print_hello()
Hello, World! from C++
Boost.Python can be used to do some pretty magic things, including exposing classes, wrapping overloaded functions, exposing global and class variables for reading and writing, hybrid Python/C++ inheritance heirarchies, all with the utility of dramatic performance gains. I recommend going through these docs and getting to know the API if you are looking to go down this route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With