How To Convert Python Code to C++

C++ is a popular, object-oriented programming language used for creating high-performance software, particularly operating systems, video games, and computer graphics applications.

Web browsers, financial apps, and embedded systems for things like medical gear and automobile electronics are also developed using it.

C++ is renowned for its capacity to interact with low-level hardware components, support for cutting-edge web technologies, and effective management of enormous volumes of data.

At several places python code is required to be replaced by C++ code. C++ provides various features which are not present in python such as increment or decrement operators.

Why Is There A Need To Convert Python Code to C++

There are several reasons for converting C++ code to Python code, including the following:

  • Efficiency: C++ is a compiled language and Python is interpreted, so c++ code executes faster than python code.
  • Less Computational Resources: As compared to python,  C++ is takes less computational resources such as processor and RAM because it is a lightweight programming language.
  • Support Pointers: Python is a high-level language and object oriented programming it is limited to implement pointers. But C++ supports implementation of pointers.

Approaches to Convert Python Code to C++

Numerous approaches may be used to convert python code to C++. There are some approaches listed and discussed below. 

  • Approach-1: Using Python to C++ Compiler
  • Approach-2: Using SWIG
  • Approach-3: Using Manually rewriting the code

Lets dive in details for each approach.

Approach-1: Using Python to C++ Compiler

Python code may be automatically converted to C++ code using one of the available Python-to-C++ compilers. The Python-to-C++ compilers Cython, Shed Skin, and Pythran are a few examples.

Algorithm:

Step-1: Select a Python to C++ compiler to work with. The choices are Cython, Shed Skin, and Pythran.

Step-2: Install the compiler and any necessary dependencies.

Step-3: Convert the Python code to a layout that the compiler can understand. For instance,

Step-4: Cython mandates the use of a unique syntax that incorporates additional type information while writing Python code.

Step-4: Create the C++ code using the compiler. Depending on the compiler being used, specific instructions may be necessary, but generally speaking, the procedure comprises running a command or script that accepts Python code as input and outputs equivalent C++ code.

Step-5: Directly create a standalone executable or library from the C++ code.

To demonstrates this approach, a program is created which code is given below:

Python  Code:

# Python code to find prime number
def isPrime(n):
	if n <= 1:
    	return False
	elif n == 2:
    	return True
	else:
    	for divisor in range(2, int(n**0.5) + 1):
        	if n % divisor == 0:
            	return False
    	return True
print(isPrime(7))
print(isPrime(15)

Output:

Python code output
True
False 

C++ Code

// C++  program to find prime number 
using namespace std;
bool isPrime(int n) {
	if (n <= 1)
{  return false;
        	} else if (n == 2) {
        	  return true;
        	  } else
 {
        	for (int divisor = 2; divisor <= sqrt(n); divisor++) {
        	if (n % divisor == 0) {
            	return false;
        	}
 }
    	return true;
	}
}
int main() {
	cout << isPrime(7) << endl;  // output: 1 (true)
	cout << isPrime(12) << endl; // output: 0 (false)
	return 0;
}

Output:

1   0

Approach-2: Using SWIG

Using the SWIG (Simplified Wrapper and Interface Generator) tool, C++ code that encapsulates a Python module or class may be generated automatically. This makes it possible to identify Python code from C++ code, and vice versa. SWIG works by studying the Python code and generating a C++ interface that can be used to call the Python code. When integrating Python code with existing C++ codebases, this method is helpful.

An algorithm for this approach is represented in the following steps.

Algorithm: 

Step-1: Install  SWIG on  device.

Step-2: Write the Python code necessary to implement the desired functionality, being sure to keep the code modular and reusable.

Step-3: Codify the SWIG interface in the Python file. Which Python features must be SWIG-wrapped in order to be utilized in C++ programming, according to this code. The SWIG interface code must contain directives that tell SWIG how to build C++ code as well as prototypes of C++ features that match to the Python features being wrapped.

Step-4: Use SWIG to convert the Python source code and interface code into a C++ wrapper record. Using the command line or a construction system like CMake, this can be done.

Step-5: Create the C++ code that utilizes the produced by SWIG wrapper capabilities

Step-6: The SWIG-generated header file and a link to the SWIG-generated item record must be included in the C++ code.

Step-7: Link the C++ code against the Python library and all other necessary libraries after compiling it.

Step-7: Check the C++ code to make sure it works as intended and achieves the desired results.

Python  Code:

# Python program to demonstrate to check whether given number is prime or not
def isPrime(n):
	if n <= 1:
    	return False
	elif n == 2:
    	return True
	else:
    	for divisor in range(2, int(n**0.5) + 1):
        	if n % divisor == 0:
            	return False
    	return True
print(isPrime(7))
print(isPrime(15)

Output:

True
False

C++ Code

Write the "isPrime.I" SWIG interface file. A statement for the "isPrime" feature must be included in this file so that SWIG knows which Python function to convert to C++. The interface record's code is shown below:
%module isPrime
%{
#include "isPrime.h"
%}
bool isPrime(int n);
Run the SWIG tool on the Python code and the interface document. By doing this, a collection of C++ files will be created, encasing the Python code and making it usable from C++. Your operating system and SWIG installation will determine the exact command you use, but here is an example for Linux:
swig -c++ -python isPrime.I
 C++ Code
import isprime
print(isprime.isPrime(7))
print(isprime.isPrime(15))

Output:

1
0

Approach-3: Using Manually Rewriting the Code

This method calls on a solid command of both Python and C++, as well as the ability to convert the Python code’s logic into equivalent C++ code.

Algorithm

Step-1: Analyze the Python code to determine its fundamental structure and any functions or procedures that need to be converted to C++.

Step-2: Convert the Python syntax into the corresponding C++ syntax.

Step-3: Using only the Python code, determine the appropriate statistical types for variables and function arguments in C++.

Step-4: Rewrite the loops and conditional statements in the manage go with the flow statements using C++ syntax.

Step-5: If required, substitute C++ libraries for any Python-specific features or modules.

Step-6: Make sure the translated C++ code achieves the same results as the original Python code by manually checking it for accuracy.

Step-7: If required, utilize strategies like pre-computing values or reducing needless memory allocations to optimize the C++ code for speed.

Python  Code:

# Python program to check given number is prime or not using approach-3 
def isPrime(n):
	if n <= 1:
    	return False
	elif n == 2:
    	return True
	else:
    	for divisor in range(2, int(n**0.5) + 1):
        	if n % divisor == 0:
            	return False
    	return True
print(isPrime(7))
print(isPrime(15)

Output:

True
False

C++ Code:

// C++ code for manual translation of python to C++ code conversion 
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n) {
	if (n <= 1) {
    	return false;
	} else if (n == 2) {
    	return true;
	} else {
    	for (int divisor = 2; divisor <= sqrt(n); divisor++) {
        	if (n % divisor == 0) {
            	return false;
        	}
    	}
    	return true;
	}
}
int main() {
	// Example usage:
	cout << isPrime(7) << endl;	// Output: 1 (true)
	cout << isPrime(15) << endl;   // Output: 0 (false)
return 0;
}

Output:

1
0

Best Approach- Using SWIG

The SWIG technique is a well-liked option for converting Python code to C++ since it can create callable C++ code from numerous programming languages including Python, integrating C++ code into current Python projects. SWIG is an effective tool for translating Python to C++ because it is simple to use, has the ability to handle complicated data types, and adheres to object-oriented conventions. Apart from that, the following reasons are to say this approach is the best approach.

  • Easy Access: SWIG method allows programmers to convert any language code in C++ or C code.
  • Performance: It enables fast conversion compared to other methods.

Sample problems related to convert Python Code to C++

Sample Problem-1: Using Approach-1

Problem Definition:Convert area of triangle Python code to C++ code using python to C++ compiler

Solution: An algorithm for this problem is represented in the following steps.

Algorithm:

Step-1: Choose a Python to C++ compiler to use for your project. Cython, Shed Skin, PyOxidize rand Pythran are the options.

Step-2: Install any required dependencies as well as the compiler.

Step-3: Change the Python code’s format so that the compiler can read it. For instance, while developing Python code, Cython requires the usage of a special syntax that includes additional type information.

Step-4: Use the compiler to write the C++ code. Specific instructions may be required depending on the compiler being used, but generally speaking, the process entails executing a command or script that accepts Python code as input and produces comparable C++ code.

Step-5: Directly convert the C++ code into a standalone executable or library. Again, depending on the compiler being used, the precise steps required to do this can vary, but in general, the process comprises executing a command or script that transforms the C++ code into an executable or library that can be used on the target platform.

To demonstrates this approach, a program is created which code is given below:

Python Code:

# Python code to demonstrate calculation of area of triangle
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
calculate the semi-perimeter
s_val = (a + b + c) / 2
calculate the area
area_val = (s_val*(s_val-a)(s_val-b)(s_val-c)) ** 0.5
print('The area of the triangle is %0.2f' %area_val)	

Output:

Enter first side: 5
Enter second side: 6 
Enter third side: 7
The area of the triangle is 14.70

C++ Code:

// C++ program for the calculation of area of rectangle
#include <Python.h>
int main(int argc, char** argv) {
	Py_Initialize();
	// Execute the Python code
	PyRun_SimpleString(R"(
    	a = float(input('Enter first side: '))
    	b = float(input('Enter second side: '))
    	c = float(input('Enter third side: '))
    	s_val = (a + b + c) / 2
    	area_val = (s_val * (s_val - a) * (s_val - b) * (s_val - c)) ** 0.5
    	print(f'The area of the triangle is {area_val:.2f}')
	)");
	Py_Finalize();
	return 0;
}

Output:

Enter first side: 5
Enter second side: 6
Enter third side: 7
The area of the triangle is 14.70

Code Explanation:

● The input() function of the Python programming language is used to receive user input and compute the rectangle’s area using the input values.

● It’s crucial to change the code when using a Python to C++ compiler to utilise C++ input methods rather than input()

● To use the appropriate C++ syntax for arithmetic operations.

Sample Problem-2: Using Approach-2

Problem Definition:  Convert the largest number among the three input numbers Python code  to C++ code using SWIG

Solution: An algorithm for this approach is represented in the following steps.

Algorithm: 

Step-1:  A file with the “.py” suffix should contain the Python code.

Step-2: Make a file with the “.i” suffix for an interface.

Step-3: Use Python syntax to define the function (task) that will be bound in the interface file.

Step-4: To execute SWIG on the interface file, use the relevant command for your system.

Step-5: Your C++ project should now contain the created C++ wrapper code.

Step-6: From your C++ code, call the constructed function or functions.

Python Code:

# Python code to find largest number among three numbers 
#new_num1 = float(input("Enter first number: "))
#new_num2 = float(input("Enter second number: "))
#new_num3 = float(input("Enter third number: "))
if (new_num1 >= new_num2) and (new_num1 >= new_num3):
   largest_val = new_num1
elif (new_num2 >= new_num1) and (new_num2 >= new_num3):
   largest_val = new_num2
else:
   largest_val = new_num3
print("The largest number is", largest_val)

Output:

Enter first number: 4.6
Enter second number: 5.4
Enter third number: 6.0
The largest number is 6.0

C++ Code:

// Equivalent C++ code to find largest number among three numbers
%
module largest
%{
#include <iostream>
using namespace std;
%}
%include <windows.i>
%include <exception.i>
%include <std_string.i>
%inline %{
	double find_largest(double num1, double num2, double num3) {
    	double largest_val;
    	if (num1 >= num2 && num1 >= num3)
        	largest_val = num1;
    	else if (num2 >= num1 && num2 >= num3)
        	largest_val = num2;
    	else
        	largest_val = num3;
    	return largest_val;
	}
%}

Output:

Enter first number: 6.8
Enter second number: 15.4
Enter third number: 2.4
The largest number is 15.4

Code Explanation:

  • The biggest of the three integers is determined by the code above using conditional information.
  • The input and output parameters for the function must be specified if SWIG is being used to translate this code to C++.
  • Other programming languages can call the SWIG-generated C++ code, giving the project an interface.

Sample Problem-3: Using Approach-3

Problem Definition: Convert the  Fibonacci sequence Python code  to C++ code.

Solution: An algorithm for this problem is represented in the following steps.

Algorithm: 

Step-1: Write the Python code you wish to understand first.

Step-2: Identify any Python-specific grammar or code elements (such the input() method or Python-specific libraries) that will not translate to C++.

Step-3: Replace any Python-specific syntax or construction with a C++ equivalent. For example, replace input() with cin, and use a standard C++ library instead of a Python-specific one.

Step-4: Write the code again using C++ syntax while maintaining the Python version’s logic and method.

Step-5: Pay particular attention to how Python and C++ vary from one another in terms of variable types and syntax. In contrast to Python, C++ mandates the explicit declaration of variables and their associated data types.

Python Code:

# Python code to find fibonacci series
num_terms = int(input("How many terms? ")) 
# first two terms
prev_term, curr_term = 0, 1
count = 0
# check if the number of terms is valid
if num_terms <= 0:
   print("Please enter a positive integer")
# if there is only one term, return prev_term
elif num_terms == 1:
   print("Fibonacci sequence upto", num_terms, ":")
   print(prev_term)
# generate fibonacci sequence
else:
   print("Fibonacci sequence:")
   while count < num_terms:
   	print(prev_term)
   	next_term = prev_term + curr_term
   	# update values
   	prev_term = curr_term
   	curr_term = next_term
   	count += 1

Output:

Please enter a positive integer 5
Fibonacci sequence: 1 1 2 3 5 8 13

C++ Code:

// Equivalent C++ code of python program to find fibonacci series for given number 
#include <iostream>
using namespace std;
int main() {
	int num_terms, prev_term = 0, curr_term = 1, count = 0;
	// get the number of terms from the user
	cout <<"How many terms? ";
	cin >> num_terms;
	// check if the number of terms is valid
	if (num_terms <= 0) {
    	cout <<"Please enter a positive integer"<< endl;
	}
	// if there is only one term, return prev_term
	else if (num_terms == 1) {
    	cout <<"Fibonacci sequence upto "<< num_terms <<":"<< endl;
    	cout << prev_term << endl;
	}
	// generate fibonacci sequence
	else {
    	cout <<"Fibonacci sequence:"<< endl;
    	while (count < num_terms) {
        	cout << prev_term << endl;
        	int next_term = prev_term + curr_term;
        	// update values
        	prev_term = curr_term;
        	curr_term = next_term;
        	count++;
    	}
	}
	return 0;
}

Output:

Please enter a positive integer 5
Fibonacci sequence: 1 1 2 3 5 8 13

Code Explanation:

  • In order to convert Python code to C++,
  • it is necessary to comprehend its logic and functioning.
  • This is done by identifying the data types and suitable C++ syntax.

Conclusion

Python is an interpreted language but C++ is a compiled language, providing for more direct hardware access and memory management. For some applications, C++ can also offer quicker execution times and greater performance. Here, several approaches for converting a python code to C++ were presented with an algorithm, program, output and its explanation. A SWIG approach is considered as the best approach because it offers fast access and efficiency.