A quick guide on how to write Python code that cleanly translates into C++ using the Py2Cpp compiler.
Py2Cpp automatically converts many Python types and annotations into C++ equivalents.
Python
x: int = 10C++
int x = 10;Python
y: float = 3.14C++
double y = 3.14;Python
name: str = "abc"C++
std::string name = "abc";Function definitions with type hints are converted into C++ functions.
Python
def add(a: int, b: int) -> int:
return a + bC++
int add(int a, int b) {
return a + b;
}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";Some ctypes types are directly converted into native C++ types.
Python
x = c_ulonglong(1)C++
unsigned long long x = 1ULL;Use @c_struct to define simple data structures. These become C++ struct definitions.
Python
@c_struct
class Position:
x: float
y: floatC++
struct Position {
double x;
double y;
};Some Python syntax does not map cleanly to C++ and is therefore disallowed.
*Class@c_struct.cpp file.g++ -std=c++20).Tips for Writing Py2Cpp-Compatible Code
@c_struct instead of normal classes when possible.Final[] for constants.