Utilise Cython at Lowest Level

File Extensions

Cython allows integrating with C++ code, however, Cython will generate files to .h and .cpp extensions, so .hpp extension is avoided not to be confused as going along with the .cpp file.

Use these extensions instead:

  • .hh for header files (to use with .pxd files)
  • .cc for implementation files (to use with .pyx files)

Why C++ Header Files

Cython has no forward declaration, declaring a type in Cython with name only will actually create empty type, not forward declaration. Thus, use C++ header files to contain forward declaration which is required when having circular dependencies.

Why C++ Implementation Files

Some low-level features are only, or at least only convenient in C++.

.pxd File with C++ Header

In order to use mymod.hh , redeclare the stuff in the C++ header file in .pxd file.
File mymod.hh:

#ifndef MYMOD_HH
#define MYMOD_HH

// My class
class my_class{
public:
    int my_prop;
public:
    void my_method();
};

#endif

File mymod.pxd:

# Redeclare what to use, not all props & methods required
cdef extern from "mymod.hh":
    cppclass my_class:
        int my_prop;

.pyx File with C++ Implementation

In order to compile Cython code together with C++ code, include the C++ source code into .pyx file.
File mymod.cc:

#include <cstdio>

// My method
void my_class::my_method(){
    printf("My text!");
}

File mymod.pyx:

# distutils: language=c++

# Include C++ source code
cdef extern from "mymod.cc":
    pass

You'll only receive email when they publish something new.

More from 19411
All posts