python to c++ converter

I am looking for python to c++ converters. Any free tools available?
There's Python to executable, but I don't think there's a reliable Python to C++ converter. That kind of conversion has to happen by hand.
Do you need to convert anything?
https://duckduckgo.com/?q=call+python+from+c%2B%2B&t=newext&atb=v305-1&ia=web
https://duckduckgo.com/?q=call+c%2B%2B+from+python&t=newext&atb=v305-1&ia=web

Maybe you don't need to convert the whole program to C++, just the bit doing the intensive work.
PyInstaller as well as py2exe can create a single EXE file from your Python program:
https://pypi.org/project/py2exe/
https://pyinstaller.org/en/stable/index.html

But this does not really convert your Python code to "native" code (e.g. translate it to C/C++ and then compile it), but instead it simply bundles the Python interpreter together with all the required .py files into a single "fully self-contained" package (e.g. EXE file).

________

You can also write a Python extension module in C/C++ and then call it from your "normal" Python code:
https://docs.python.org/3/extending/extending.html
https://realpython.com/build-python-c-extension-module/#extending-your-python-program

This way you can write certain performance-critical functions of your program in C/C++ code, while the main "business logic" of your program can remain in normal Python code. This could be better than re-writing the whole program in C/C++.

________

Last but not least, if performance is your primary concern here, then have a look at the PyPy project:
https://www.pypy.org/

This runs standard Python code without any changes, but often is many times faster than the "official" Python interpreter (CPython).
Last edited on
I don't know if under the hood the "cython" converts to C or C++ as an intermediate step or if it just bypasses the weirdint type in favor of CPU int types and similar basic fixes? There are a number of one-off python stepchildren like cython and scipy or whatever the "scientific" one is called. These usually are tailored to give intermediate performance instead of the normal python extra slow performance, or have some other gimmick that lets you do something differently.

In all honesty, I have a strong dislike for language converters. Most of them just spew horrible, unreadable, unfixable code that may or may not be exactly identical to the original. To put it in perspective, grab some text from any natural language and run it through the free translators into english or anything you understand and see what a mess it makes? Its sometimes marginally readable, but you can always tell it was written by a machine due to dumb word choices and other mistakes. The same is true for source code translators.
I need to fully convert a python code to c++. Can anyone help me on this?
I searched and found below python to c++ converter,but not sure if its accurate. Has anyone tried this ?
https://github.com/alxschwrz/codex_py2cpp

> Can anyone help me on this?
http://www.catb.org/~esr/faqs/smart-questions.html#prune

> Has anyone tried this ?
Why can't you try it?

Especially since you seem to be in no mood to divulge the Python code you want to convert.

FWIW, it looks like a proof of concept toy to play with.
Not something production ready for any random blob of Python code you happen to have.
I wouldn't trust that Python to C++ converter much. Some things can't be directly converted and it's possible to find a situation where some interpretation of the code is needed in order to properly convert.
@denver2020,
The languages are very different, so any automatic converter is unlikely to exploit the particular idioms of the languages very effectively. Also, the resulting C++ is unlikely to be very readable, up-to-date or even correct.

You would be better learning both languages and doing it manually. You might even discover ... that it doesn't make sense to do it in the first place.

What particular piece of Python do you want to convert?
I searched and found below python to c++ converter,but not sure if its accurate. Has anyone tried this ?
https://github.com/alxschwrz/codex_py2cpp
codex_py2cpp apparently is based on an "A.I." cloud service called OpenAI Codex. Consequently, you need access to their (i.e. OpenAI Codex) Web-API in order to use the "codex_py2cpp" program. I don't have such access, so can't test this tool.

Anyway, it essentially means that they have trained a neural network (or something in that vein) to generate "plausible looking" C++ code from the given Python code. This may give impressive results in some cases, but may produce complete gibberish in other cases. But, most important: For any non-trivial input program, it will be next to impossible to proof that the "A.I.-generated" C++ code accurately resembles the original Python code. The "Example Code Generation" on the website is way too trivial to judge the quality of the code...
Last edited on
"In this video, I am showing you how you can use Facebook's AI Code Translator. This Translator can convert Your Python code to Java & C++, even vice versa also."

https://www.youtube.com/watch?v=cKUEvbzcCQ4

You can also check out SWIG:

https://www.swig.org
Hi lastchance

I am trying to convert the below python code to c++. Any inputs here?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

def normal_pdf(x, mean, var):
    return np.exp(-(x - mean)**2 / (2*var))

xmin, xmax, ymin, ymax = (0, 100, 0, 100)
n_bins = 100
xx = np.linspace(xmin, xmax, n_bins)
yy = np.linspace(ymin, ymax, n_bins)
means_high = [20, 50]
means_low = [50, 60]
var = [150, 200]
gauss_x_high = normal_pdf(xx, means_high[0], var[0])
gauss_y_high = normal_pdf(yy, means_high[1], var[0])
gauss_x_low = normal_pdf(xx, means_low[0], var[1])
gauss_y_low = normal_pdf(yy, means_low[1], var[1])
weights = (np.outer(gauss_y_high, gauss_x_high)
           - np.outer(gauss_y_low, gauss_x_low))
greys = np.full((*weights.shape, 3), 70, dtype=np.uint8)
vmax = np.abs(weights).max()
imshow_kwargs = {
    'vmax': vmax,
    'vmin': -vmax,
    'cmap': 'RdYlBu',
    'extent': (xmin, xmax, ymin, ymax),
}

fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, **imshow_kwargs)
ax.set_axis_off()
alphas = np.ones(weights.shape)
alphas[:, 30:] = np.linspace(1, 0, 70)
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)
ax.set_axis_off()

alphas = Normalize(0, .3, clip=True)(np.abs(weights))
alphas = np.clip(alphas, .4, 1)  # alpha value clipped at the bottom at .4
fig, ax = plt.subplots()
ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)
ax.contour(weights[::-1], levels=[-.1, .1], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()
ax.contour(weights[::-1], levels=[-.0001, .0001], colors='k', linestyles='-')
ax.set_axis_off()
plt.show()

 
I am trying to convert the below python code to c++


Yes, but more than half of that code is using the python graphics library, matplotlib. C++ doesn't have such a graphics library in the standard: you would have to use a 3rd-party library to do the plotting.

You would do better to leave it in Python. Those NumPy arrays are very fast and very flexible.


BTW - your normal PDF is wrong ... it's missing the normalising factor 1/(sigma.sqrt(2.pi)).



The first half of the code translates to something like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

//======================================================================

vector<double> normal_pdf( const vector<double> &x, double mean, double var )
{
   int N = x.size();
   vector<double> V( N );
   for ( int i = 0; i < N; i++ ) V[i] = exp( -0.5 * ( x[i] - mean ) * ( x[i] - mean ) / var );
   return V;
}

//======================================================================

vector<double> linspace( double a, double b, int N )
{
   vector<double> V( N );
   double dx = ( b - a ) / ( N - 1 );
   for ( int i = 0; i < N; i++ ) V[i] = a + i * dx;
   return V;
}

//======================================================================

int main()
{
   double xmin = 0, xmax = 100, ymin = 0, ymax = 100;
   int n_bins = 100;
   auto xx = linspace( xmin, xmax, n_bins );
   auto yy = linspace( ymin, ymax, n_bins );

   vector<double> means_high = { 20, 50 };
   vector<double> means_low  = { 50, 60 };
   vector<double> var = { 150, 200 };
   auto gauss_x_high = normal_pdf( xx, means_high[0], var[0] );
   auto gauss_y_high = normal_pdf( yy, means_high[1], var[0] );
   auto gauss_x_low  = normal_pdf( xx, means_low[0] , var[1] );
   auto gauss_y_low  = normal_pdf( yy, means_low[1] , var[1] );

   vector< vector<double> > weights( n_bins, vector<double>( n_bins ) );
   for ( int j = 0; j < n_bins; j++ )
   {
      for ( int i = 0; i < n_bins; i++ )
      {
         weights[i][j] = gauss_y_high[i] * gauss_x_high[j] - gauss_y_low[i] * gauss_x_low[j];
      }
   }

  // etc. etc.
}


As you can see, the C++ code is spectacularly verbose compared with Python ...
Last edited on
You can get the Python graphics capabilities in a C++ executable.

https://stackoverflow.com/questions/31145209/compile-python-and-c-together

Embed the code.

https://docs.python.org/3/extending/embedding.html
I am not looking to compile python code in c++, rather I need a converter than can convert the above python code to c++ code.
I am not looking to compile python code in c++, rather I need a converter than can convert the above python code to c++ code.

There is simply no way to directly convert it. The same way you can't convert French directly to English without someone who can interpret. An automated translator will always have errors.

Now, imagine trying to convert GUI Python to C++ like trying to convert a textbook about quantum mechanics to from French to English while you don't understand quantum mechanics.

Difficult enough for a person let alone an automated program.
Last edited on
As the others have repeatedly mentioned a Python to C++ converter is not going to give you C++ code that is idiomatic C++ code.

Or learn enough of both languages to do the conversion yourself.

Especially since the Python code does things, graphics, that are not native to the C++ stdlib. So what 3rd party C/C++ library are you going to shoehorn into your C++ code?

Don't rely on automated tools to do even a mediocre job, they usually are worse.

You'd be better off hoping for an infinite number of monkeys to craft better C++ code. Maybe the first Tuesday of the next millennium.
Having written numerous translators, I would suggest that C is a better target language. I love C++, but the problem with C++ as a target language is trying to guess what constructs in python belong in a class and what that class name should be. I find that C as a target language is less restrictive is this regard.
Last edited on
Topic archived. No new replies allowed.