How to Use Py2Cpp

A quick guide on how to write Python code that cleanly translates into C++ using the Py2Cpp compiler.

1. Basic Types

Py2Cpp automatically converts many Python types and annotations into C++ equivalents.

Python

x: int = 10

C++

int x = 10;

Python

y: float = 3.14

C++

double y = 3.14;

Python

name: str = "abc"

C++

std::string name = "abc";

2. Functions

Function definitions with type hints are converted into C++ functions.

Python

def add(a: int, b: int) -> int:
    return a + b

C++

int add(int a, int b) {
    return a + b;
}

3. Const & Final Types

Use Final[T] when you want a constant variable. Py2Cpp maps this to const in C++.

Python

from typing import Final
name: Final[str] = "abc"

C++

const std::string name = "abc";

4. ctypes → C++ Types

Some ctypes types are directly converted into native C++ types.

Python

x = c_ulonglong(1)

C++

unsigned long long x = 1ULL;

5. Structs via @c_struct

Use @c_struct to define simple data structures. These become C++ struct definitions.

Python

@c_struct
class Position:
    x: float
    y: float

C++

struct Position {
    double x;
    double y;
};

6. Unsupported Features

Some Python syntax does not map cleanly to C++ and is therefore disallowed.

  • Pointer-like expressions such as *Class
  • Dynamic typing (e.g., variables without annotations)
  • Runtime metaprogramming
  • Arbitrary decorators other than @c_struct

7. Compilation Workflow

  1. Write Python code using static types and supported annotations.
  2. Press Convert Now on the main page.
  3. Review the generated C++ code in the output panel.
  4. Download the .cpp file.
  5. Compile using your preferred C++ compiler (e.g. g++ -std=c++20).

Tips for Writing Py2Cpp-Compatible Code

  • Always include type annotations.
  • Prefer simple class structures.
  • Use @c_struct instead of normal classes when possible.
  • Use Final[] for constants.
  • Keep function signatures simple and typed.