Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to recursively include all headers when wrapping C++ in Cython

I'm trying to wrap a C++ library using Cython.

The headers themselves include other libraries to define types (actually, quite a lot), somethings like this:

#include <Eigen/Dense>

namespace abc {
namespace xyz {
typedef Eigen::Matrix<double, 5, 1> Column5;
typedef Column5 States;
}}

There are a lot of "external" type definitions. Is there a way not to write also a .pxd file for the Eigen library? I just need the type "States" available in my .pxd-file for imported (wrapped) class definitions...

like image 616
Moritz Avatar asked Oct 15 '25 04:10

Moritz


1 Answers

I am not sure about what you are asking for, but as far as I understood, I would say: Just expose what you need (here the State type).

In your .pyx or your .pxd:

(Assuming the code in your question is part of a file named my_eigen.h)

# Expose State 
cdef extern from "some_path/my_eigen.h" namespace "xyz" :
    cdef cppclass States:
        # Expose only what you need here
        pass

Once you have done the wrapping above, you are free to use State where ever you need it in Cython code.

# Use State as is in your custom wrapped class
cdef extern from "my_class_header.h" namespace "my_ns" :
    cdef cppclass MyClassUsingStates:
        double getElement(States s, int row, int col)
        ...

Example:

Here my need was: having a python handler for std::ofstream and no need to expose any of its methods (so I exposed none but it would have been possible...)

cdef extern from "<fstream>" namespace "std" :
    cdef cppclass ofstream:
        pass

cdef class Py_ofstream:
    cdef ofstream *thisptr

    def __cinit__(self):
       self.thisptr = new ofstream()

    def __dealloc__(self):
       if self.thisptr:
           del self.thisptr

Note : here I used it directly as a single block in my .pyx (no additional .pyd).

Tell me if misunderstood the question...

like image 153
Gauthier Boaglio Avatar answered Oct 16 '25 19:10

Gauthier Boaglio