How can I use python with c++?

Asked

Viewed 44 times

-3

I found that I can use two programming languages in the same program, but I don’t know exactly how to do this... I just wanted an idea in a very simple example to make the code work below and I learn.

I have a python program that has an input of the whole type (int), the user type any value in it below 300:

num = int(input("Digite o número: "))

After this I wanted to somehow pass the value of num for a C++ code that only executes a loop for with the value given in num:

//nota-se que o valor de 'a' seria o valor atribuído na variável 'num' no arquivo .py 
for(a=num; a<300; a++){
   cout << a << endl;
}

I had first thought to put for example a #include, but I don’t know if doing such a thing would result in some mistake.

1 answer

0


You have to define whether to) call C++ code from Python and/or b) call Python code from C++.

In case (a) you should search on how to extend Python and develop Python modules in C/C++. The beginning is the documentation of the language, even to understand the challenges involved: https://docs.python.org/3/extending/extending.html

There are other options that should be considered, as they are more practical: Boost.Python, Cython, SWIG, FFI, etc. The best tool will depend on your particular case.

In case (b) what you want is to do an "embedding" of the Python machine inside a C/C++ program. Basic documentation: https://docs.python.org/3/extending/embedding.html

Python is not considered the easiest language to "get drunk"; Lua wins the trophy at this point.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.