C++ Support¶
autopxd2 supports C++ headers through either parser backend.
Note
The libclang backend (the default) and the tree-sitter backend both parse C++. See Parser Backends for the trade-offs.
Basic C++ Usage¶
Or with Docker:
Supported C++ Features¶
Classes & Structs¶
C++ classes and structs are converted to Cython cppclass definitions with support for multiple inheritance, constructors, @staticmethod, and const member methods.
Destructors are not emitted: a Cython cppclass block does not declare them, and Cython calls the C++ destructor automatically for stack-allocated instances.
// widget.hpp
class BaseWidget {
public:
virtual void show();
};
class Widget : public BaseWidget {
public:
int width;
int height;
Widget();
Widget(int w, int h);
virtual ~Widget();
int area() const;
static Widget create();
};
Generates:
cdef extern from "widget.hpp":
cdef cppclass BaseWidget:
void show()
cdef cppclass Widget(BaseWidget):
int width
int height
Widget()
Widget(int w, int h)
int area() const
@staticmethod
Widget create()
Generic Function & Method Templates¶
Generic C++ function and method templates are fully supported using Cython template brackets syntax:
Generates:
Functions¶
Global functions are converted directly:
Generates:
Namespaces¶
Declarations inside a namespace are emitted in a dedicated cdef extern from ... namespace block:
// ns.hpp
namespace outer {
class Widget {
public:
Widget();
int value() const;
};
int helper(int x);
}
Generates:
cdef extern from "ns.hpp" namespace "outer":
cdef cppclass Widget:
Widget()
int value() const
int helper(int x)
Nested namespaces are joined with :::
Generates:
Limitations¶
Overloading¶
Multiple overloaded free functions with identical names may produce conflicts in C mode. In C++ mode (--cpp), Cython natively supports function overloading.
Best Practices¶
- Use header-only libraries where possible for simpler integration
- Start with the Docker image to avoid libclang installation issues
- Check generated output and manually adjust for complex C++ features
- Consider Cython's cppclass for classes with methods you need to call
Example Workflow¶
-
Generate initial pxd:
-
Review and adjust for methods, templates, or other features
-
Create your Cython wrapper: