Python is a superior, formally defined programming language renowned for its clarity, readability, and use. Web development, data analysis, machine learning, automation, scripting, and teaching are just a few of the uses.
Python contains a wide variety of well-known libraries and programmes that make it simple to work with data, create web applications, and carry out everyday activities. Because of its straightforward and simple syntax, it is also a well-liked resource for novices.
Why Is There A Need To Convert C++ Code to Python
There are various benefits of converting C++ code to Python code. There are many reasons that we require to convert C++ code into python.
- Simple and Convenient: Python is simple to use and understand.
- Computational Capabilities: Python code may show an audience that there are many more options accessible, particularly in data science and machine learning.
- Productivity: Python is a high-level language with functions and data structures that are already built-in, making it simpler to develop code rapidly and effectively.
Approaches to Convert C++ Code to Python
Numerous approaches may be used to convert C++ code to python. There are some approaches listed and discussed below.
- Approach-1: Using Manual Translation
- Approach-2: Using SWIG
- Approach-3: Using CXX
- Approach-4: Using PyBind11
Lets dive in details for each approach.
Approach-1: Using Manual Translation
This necessitates translating C++ code to Python. Manual modifications enable a developer to optimize Python code for execution, readability, and maintenance, but can be a time-consuming task.
Algorithm:
Step-1:Understanding the C++ code that has to be updated is the first step. All rule structures, variables, functions, and logic must be understood for this.
Step-2: Finding the corresponding Python syntax for each C++ construct, including variables, data types, loops, conditions, functions, and classes, is the following stage.
Step-3: The next step is to write Python code after determining the comparable Python syntax. In order to do this, C++ code must be converted to Python following the prescribed syntax.
Step-4: Python code optimization is crucial once the first line of code has been written for readability, speed, and maintenance. This can entail rearranging the code, eliminating superfluous or pointless lines of code, and tightening it even further.
Step-5: Python code must be tested and debugged in order to ensure that it works as intended and produces the expected results. To ensure that the code handles the edge case properly, it must be tested with various inputs.
To demonstrates this approach, a program is created which code is given below:
C++ Code:
// C++ program to find greater number among two numbers
#include <iostream>
using namespace std;
int main() {
int num1, num2, gcd;
cout <<"Enter two numbers: ";
cin >> num1 >> num2;
// swapping variables num1 and num2 if num2 is greater than num1.
if ( num2 > num1) {
int temp = num2;
num2 = num1;
num1 = temp;
}
}
cout <<"The swapped numbers: "<< num1<<num2;
return 0;
}
Output:
Enter two numbers:20 56
The swapped numbers:56 20
Python Code
# Python Code equivalent to C++ code for find greater number among two integer number
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# swapping variables num1 and num2 if num2 is greater than num1.
if num2 > num1:
temp = num2
num2 = num1
num1 = temp
print("Swapped numbers:",num1,num2)
Output:
Enter first number: 40
Enter second number: 12
Swapped numbers:12 40
Approach-2: Using SWIG
SWIG (Simplified Wrapper and Interface Generator) is a well-liked programme for turning C++ code into Python. It supports several programming languages and gives C++ code in Python an easy method to express itself.
An algorithm for this approach is represented in the following steps.
Algorithm:
Step-1: The function that has to be constructed should be defined in a C++ interface file.
Step-2: Make a header file that lists the C++ functions that must be constructed.
Step-3: Use SWIG to encapsulate C++ programmes in Python.
Step-4: Create a Python function that calls the produced C++ function with the specified input values after importing the built module.
Step-5: Create a Python function, compile it, and use it to determine the GCD value.
Step-6: Show the user the GCD value.
C++ Code:
// C++ program to demonstrates GCD
#include <iostream>
using namespace std;
int main() {
int num1, num2, gcd;
cout <<"Enter two numbers: ";
cin >> num1 >> num2;
// swapping variables num1 and num2 if num2 is greater than num1.
if ( num2 > num1) {
int temp = num2;
num2 = num1;
num1 = temp;
}
for (int i = 1; i <= num1; ++i) {
if (num1 % i == 0 && num2 % i ==0) {
gcd = i;
}
}
cout <<"GCD = "<< gcd;
return 0;
}
Output:
Enter two numbers: 15 25
GCD: 5
Python Code COnversion Mechanism
The functionality we wish to develop must first be described in a C++ interface file, such as gcd.i. We only have a function (gcd) in this situation, which accepts two numbers as input and outputs an integer:%module gcd
%{
#include “gcd.h”
%}
%include “gcd.h”
create a header file (e.g. gcd.h) that defines the gcd function:
int gcd(int num1, int num2);
Use SWIG to generate a Python wrapper for the C++ code by running the following command in the terminal:
swig -c++ -python gcd.i
Python Code:
# Python program equivalent to C++ code that demonstrates GCD of two integer numbers
import gcd
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = gcd.gcd(num1, num2)
print("GCD =", result)
Output:
Enter first number:3
Enter second number:5
GCD =1
Approach-3: Using CXX
CXX: This programme enables programmers to create Python extensions in C++. It offers a means for C++ programmers to communicate with Python and for C++ programmers to produce Python modules.
Algorithm:
Step-1: Install the CXX library in place on your computer.
Step-2: Create C++ code that is reversible.
Step-3: The CXX library’s cxxfunction() function may be used to build a Python object that can be used in C++ applications.
Step-4: Define the object’s Python interface before calling it.
Step-5: Use the specified interface to call an object that may be invoked from a Python function.
Step-6: Create a Python function, compile it, and use it to examine the altered C++ code.
Step-7: Show the user the results.
C++ Code:
// C program to demonstrates find GCD of two integer numbers
#include <iostream>
using namespace std;
int main() {
int num1, num2, gcd;
cout <<"Enter two numbers: ";
cin >> num1 >> num2;
// swapping variables num1 and num2 if num2 is greater than num1.
if ( num2 > num1) {
int temp = num2;
num2 = num1;
num1 = temp;
}
for (int i = 1; i <= num1; ++i) {
if (num1 % i == 0 && num2 % i ==0) {
gcd = i;
}
}
cout <<"GCD = "<< gcd;
return 0;
}
Output:
Enter two numbers:3 15
GCD:3
Python Code:
# Python program equivalent to C++ code that demonstrates find GCD for two integer numbers
from CXX import *
def gcd(num1, num2):
gcd = 1
if num2 > num1:
num1, num2 = num2, num1
for i in range(1, num1+1):
if num1 % i == 0 and num2 % i == 0:
gcd = i
return gcd
cfunc = cxx_function(gcd, 'int', ['int', 'int'])
print("Enter two numbers: ")
num1 = int(input())
num2 = int(input())
print("GCD = ", cfunc(num1, num2))
Output:
Enter first number: 3
Enter second number: 5
GCD = 1
Approach-4: Using PyBind11
The Python bindings for C++ libraries may be made using this little header library. It supports a large number of C++ capabilities and offers a quick and effective solution to translate C++ code to Python.
This approach is defined in the following algorithm.
Algorithm:
Step-1:Using the appropriate package manager, install PyBind11.
Step-2: Create the C++ code necessary to convert it and save it in a source C++ file.
Step-3: Add the required PyBind11 headers to the source code.
Step-4: Make a function that matches to the C++ source code that has to be changed.
Step-5: To define Python modules and bind them to function modules, use the PyBind11 PYBIND11_MODULE() macro.
Step-6: Use a C++ compiler that supports C++11 or later to create the source code.
Step-7: Utilize the bound function by importing the built module into Python as necessary.
C++ Code:
// C++ program to demonstrates find GCD for two integer numbers
#include <iostream>
using namespace std;
int main() {
int num1, num2, gcd;
cout <<"Enter two numbers: ";
cin >> num1 >> num2;
// swapping variables num1 and num2 if num2 is greater than num1.
if ( num2 > num1) {
int temp = num2;
num2 = num1;
num1 = temp;
}
for (int i = 1; i <= num1; ++i) {
if (num1 % i == 0 && num2 % i ==0) {
gcd = i;
}
}
cout <<"GCD = "<< gcd;
return 0;
}
Output:
Enter two numbers:9 27
GCD:9
Python Code:
# Python program equivalent to C++ code that demonstrates find GCD for two integer numbers
#include <pybind11/pybind11.h>
int gcd(int num1, int num2) {
int gcd;
// swapping variables num1 and num2 if num2 is greater than num1.
if ( num2 > num1) {
int temp = num2;
num2 = num1;
num1 = temp;
}
for (int i = 1; i <= num1; ++i) {
if (num1 % i == 0 && num2 % i ==0) {
gcd = i;
}
}
return gcd;
}
namespace py = pybind11;
PYBIND11_MODULE(gcd, m) {
m.doc() = "PyBind11 module for calculating the GCD of two integers using C++";
m.def("gcd", &gcd, "Calculate the GCD of two integers");
}
Output:
Enter first number: 9
Enter second number: 21
GCD = 3
Best Approach- Using SWIG
Here are the reasons to make using SWIG a best option.
- SWIG automates the process and offers a lot of flexibility.
- It can be used to produce Python code that connects to C++ libraries and supports a wide range of C++ capabilities.
- SWIG offers extensive documentation and support and is particularly effective for large assignments.
- It is a fantastic option for anyone searching for a quick and simple way to convert C++ code to Python.
- Reusing existing C++ code in your Python application is one of the main benefits of using a wrapper library.
Sample problems related to convert C++ Code to Python
Sample Problem-1: Using Approach-1
Problem Definition:Convert area of rectangle using C++ Code to Python Code Using Manual Approach.
Solution: An algorithm for this problem is represented in the following steps.
Algorithm:
Step-1: Understand the C++ code.
Step-2: Find corresponding Python syntax for each C++ construct.
Step-3: Write Python code based on the identified Python syntax.
Step-4: Optimize the Python code for readability, speed, and maintenance.
Step-5: Test and debug the Python code with various inputs to ensure its proper functioning.
To demonstrates this approach, a program is created which code is given below:
C++ Code:
#include <iostream>
using namespace std;
int main() {
float length, width, area;
cout << "Enter the length and width of the rectangle: ";
cin >> length >> width;
area = length * width;
cout << "The area of the rectangle is: " << area << endl;
return 0;
}
Output:
Enter the length and width of the rectangle: 2.5 4.5
The area of the rectangle is: 11.25
Python Code:
# Python program equivalent to C++ program that find area of rectangle
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print("The area of the rectangle is:", area)
Output:
Enter the length of the rectangle: 4.5
Enter the width of the rectangle: 2.5
The area of the rectangle is: 11.25
Code Explanation:
- Using the user-inputted length and width values, the provided C code determines the location of a rectangle.
- The code uses fundamental I/O capabilities to capture user input and print output.
- The variable names are changed while the code’s grammar and common sense are preserved when using the manual translation approach.
Sample Problem-2: Using Approach-2
Problem Definition: Convert the power of any number C++ program to Python code using SWIG.
Solution: An algorithm for this approach is represented in the following steps.
Algorithm:
Step-1: Import the necessary C header files and SWIG modules. In Python, define the base and exponent entry variables.
Step-2: A C wrapper feature that calls the strength function from the C header file can be made using SWIG.
Step-3: The SWIG wrapper code should be converted into a shared library.
Step-4: Python should be used to import the shared library with the SWIG-generated module.
Step-5: Passing the required enter variables when calling the C wrapper feature from Python.
Step-6: Python code should print the energy characteristic result.
C++ Code:
using namespace std;
int main()
{
int pow;
float base, res = 1;
cout << "Enter base and exponent respectively: ";
cin >> base >> pow;
cout << base << "^" << pow << " = ";
while (pow != 0) {
res *= base;
--pow;
}
cout << res;
return 0;
}
Output:
Enter base and exponent respectively: 2 3
8
Python Code:
%module power
%{
#include <iostream>
using namespace std;
int power(int base, int exponent) {
int res = 1;
while (exponent != 0) {
res *= base;
--exponent;
}
return res;
}
%}
%include <std_string.i>
%include <iostream.i>
extern int power(int base, int exponent);
swig -c++ -python power.i
g++ -c power.cpp power_wrap.cxx -I/usr/include/python3.8
g++ -shared power.o power_wrap.o -o _power.so
import power
print(power.power(2, 3)) # output: 8
Output:
Enter base and exponent respectively: 4 2
16
Code Explanation:
- The provided code uses the exponent submitted by the user to compute the energy of a specific base.
- The SWIG interface record, which is used to build the wrapper code in both C++ and Python, is created when SWIG is used to convert this code to Python.
- After that, a Python application can import and use the produced Python module.
- SWIG facilitates the integration of C++ and Python code while maximizing code reuse and reducing development time.
Sample Problem-3:Using Approach-3
Problem Definition:Convert the Fibonacci sequence C++ code to Python code using CXX.
Solution: An algorithm for this problem is represented in the following steps.
Algorithm:
Step-1:Import the necessary C++ header files and SWIG modules.
Step-2: In Python, define the base and exponent entry variables.
Step-3: A C++ wrapper feature that calls the strength function from the C++ header file may be made using SWIG.
Step-4: The SWIG wrapper code should be converted into a shared library.
Step-5: Python should be used to import the shared library with the SWIG-generated module.
Step-6: Passing the required enter variables when calling the C wrapper feature from Python.
Step-7: Python code should print the energy characteristic result.
C++ Code:
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "The " << n << "th number in the Fibonacci sequence is: " << fibonacci(n) << endl;
return 0;
}
Output:
n=10
0 1 1 2 3 5 8 13 21 34
Python Code:
import cxx
# Load the shared object file containing the Fibonacci function
fibonacci = cxx.load('fibonacci.so').fibonacci
# Call the Fibonacci function and print the result
n = int(input('Enter a number: '))
print('The', n, 'th number in the Fibonacci sequence is:', fibonacci(n))
Output:
n=10
0 1 1 2 3 5 8 13 21 34
Sample Problem-4:Using Approach-4
Problem Definition: Convert the LCM C++ code to Python code using approach-4
Solution: An algorithm for this problem is represented in the following steps.
Algorithm:
Step-1: Create a separate file called lcm and define the C property calculate_lcm in it.Cpp.
Step-2: Create a new file called principal.Include the header file pybind11.H in Cpp.
Step-3: Utilizing the PYBIND11_MODULE macro, make a Python module called lcm.
Step-4: Create a Python characteristic within the module that calls the C method calculate_lcm.
Step-5: Making use of the appropriate compiler instructions, compiling the C code and producing a shared library.
Step-6: To determine the LCM of numbers entered , import the lcm module into a Python script and use the Python functionality explained in step four.
C++ Code:
include <iostream>
using namespace std;
int main()
{
int num1, num2, max;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
// maximum value between num1 and num2 is stored in max
max = (num1 > num2) ? num1 : num2;
do
{
if (max % num1 == 0 && max % num2 == 0)
{
cout << "LCM = " << max;
break;
}
else
++max;
} while (true);
return 0;
}
Output:
N1=4
N2=6
LCM =12
Python Code:
pip install pybind11
#include <pybind11/pybind11.h>
#include "lcm.cpp"
namespace py = pybind11;
PYBIND11_MODULE(lcm, m) {
m.doc() = "lcm module";
m.def("calculate_lcm", &calculate_lcm, "A function that calculates the LCM of two numbers.");
}
terminal window, navigate to the directory containing the two files, and run the following command to compile the C++ code and create the Python module:
g++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` lcm.cpp main.cpp -o lcm`python3-config --extension-suffix`
import lcm
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
lcm_value = lcm.calculate_lcm(n1, n2)
print("LCM =", lcm_value)
Output:
N1=4
N2=6
LCM =12
Code Explanation:
- A C++ programme is used to determine the LCM of two integers.
- We have developed a Python module that exposes the calculate_lcm method specified in the lcm when we use PyBind11.record in C++.
- The module is made using the PYBIND11_MODULE macro, and its feature accepts integer parameters and returns the LCM.
- We may utilize C++ code from Python and take advantage of C++ overall speed benefits by compiling the C++ code and expanding the Python module.
Conclusion
Python has several benefits over C++, including a simple syntax and a huge selection of powerful libraries.
SWIG is a tool that may be used to develop interfaces between Python and other languages in addition to C++. SWIG can be helpful when working with large, complex C libraries that need to be accessible from other languages.
Hence SWIG approach is considered as the best approach because it offers reliability and flexibility.