Overview
Shed Skin translates Python code into standalone C++ code that can be compiled and integrated into C++ projects. Understanding the generated code structure helps with optimization, debugging, and integration.Generated Code Structure
For a Python modulemymodule.py, Shed Skin generates:
mymodule.hpp- Header file with declarationsmymodule.cpp- Implementation file with definitions
Header File Structure
- Namespace
__mymodule__wraps all module contents - Classes inherit from
pyobjbase class - Template instantiations for polymorphic types
Implementation File Structure
shedskin/cpp.py via the GenerateVisitor class.
Type Mappings
Python types map to C++ types as follows:
Most types are heap-allocated and use pointers, with automatic memory management via the Boehm GC.
Boehm Garbage Collector Integration
Shed Skin uses the Boehm-Demers-Weiser conservative garbage collector for automatic memory management.Memory Allocation
All heap allocations go through GC-aware allocators:new operator is overridden to use GC_malloc() instead of standard malloc().
GC Configuration
The garbage collector is initialized inbuiltin.cpp:__shedskin__::__start():
Disabling GC
For specialized use cases, compile without GC:Calling Conventions
Calling Shed Skin from C++
To use Shed Skin generated code from C++:- Include the module header:
- Initialize the Shed Skin runtime:
- Handle Shed Skin types:
Calling C++ from Shed Skin
Extend Shed Skin with custom C++ code:- Create a builtin module stub in
~/.shedskin/mycpp.py:
- Implement in C++ as
mycpp.cppandmycpp.hpp:
- Use in Python code:
Virtual Method Tables
For class hierarchies with inheritance, Shed Skin generates virtual method tables:shedskin/virtual.py:virtuals()
Virtual dispatch allows polymorphic behavior:
Template Specialization
Polymorphic functions generate multiple template specializations:shedskin/infer.py:cpa()
Exception Handling
Python exceptions map to C++ exceptions:Exception * in the runtime.
Integrating with Existing C++ Projects
As a Static Library
- Compile Shed Skin code to object files:
- Link with your project:
- CMake integration:
As a Python Extension Module
Compile Shed Skin code as a Python extension:mymodule.so importable from Python:
Performance Considerations
Inlining
Small functions may be inlined for performance. Mark withinline:
Avoiding Virtual Calls
Virtual method calls have overhead. When possible, use final classes:Memory Locality
Keep related data together for cache efficiency:Debugging Generated Code
Enable debugging symbols:Further Reading
- Shed Skin runtime source:
shedskin/lib/builtin.cpp - Code generation implementation:
shedskin/cpp.py - Boehm GC documentation: https://www.hboehm.info/gc/