4

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...

Moritz
  • 1,085
  • 1
  • 8
  • 20

1 Answers1

3

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...

Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85
  • Thanks! I'll give it a try. Currently I'm struggeling with cython compiling (my setup.py), so it may take a while. – Moritz Jun 26 '13 at 18:10
  • @user2055010 I already wrote some things that might be useful to you [here](http://stackoverflow.com/a/16806261/1715716) and [here](http://stackoverflow.com/a/16994414/1715716). It may help. – Gauthier Boaglio Jun 26 '13 at 20:13
  • 1
    Thank you for these setup.py's! They are now stored as references ;) because in most "tutorials" you find online, they omit the importand "include_dirs" etc. parts. Meanwhile, I managed to get things compiled using the "cythonize" from Cython.Build . – Moritz Jun 26 '13 at 20:56
  • 1
    Basically, your answer was just right. I was confused because from the tutorials I was convinced that your `cdef`s had to expose _all_ of the C++ module. – Moritz Jun 26 '13 at 21:03
  • Glad to help. ;) If I can do more, just ask ! – Gauthier Boaglio Jun 26 '13 at 21:05