0

When I want to use .pxd and .pyx files to use my C++ code within Python, I can use vector after importing libcpp.vector within the pxd file. Is it possible to write own C++ classes and use them in pxd files like vector is used (for example use std::array)?

On the one hand, libcpp seems to contain the pxd file for vector only, while on the other hand the cython compiler seems to do some extra tricks when dealing with vectors.

1 Answers1

0

There are two parts to Cython's wrapping of types such as std:: vector:

  1. The .pxd files it defines for your to cimport (e.g. https://github.com/cython/cython/blob/master/Cython/Includes/libcpp/vector.pxd). These are provided for your convenience (to save everyone the effort of re-writing the same files). They use standard Cython syntax and you can create similar files to wrap other classes.

  2. The auto-conversion to/from Python types documented here. This is built in to Cython and you cannot apply it to other types that you wrap. This should not prevent you from creating a usable wrapping though - you may just need to copy a little more data manually at the Python/C++ interface.

Wrapping std::array in Cython is a bit challenging since Cython cannot readily handle numeric template arguments. There are a variety of tricks to persuade it to work that you can find on Stack Overflow and elsewhere (Interfacing C++11 array with Cython, Wrapping std::array in Cython and Exposing it to memory views) but none of them are great.

DavidW
  • 29,336
  • 6
  • 55
  • 86