Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++-style internal typedefs possible in Cython?

In C++ it's possible to declare type aliases that are members of a class or struct:

struct Foo
{
    // internal type alias
    typedef int DataType;

    // ...
};

Is there any way to do the same thing in Cython? I've tried the most obvious approach:

cdef struct Foo:
    ctypedef int DataType

But this doesn't work:

Error compiling Cython file:
------------------------------------------------------------
...
# distutils: language=c++

cdef struct Foo:
    ctypedef int DataType
   ^
------------------------------------------------------------

internal_typedefs_example.pyx:4:4: Expected an identifier, found 'ctypedef'

Is this just a fundamental limitation of Cython (I'm using v0.21.2), or is there a workaround?


Why bother with internal typedefs? There are several general reasons - this previous SO question covers a few of them.

The specific case I'm interested in is wrapping a set of templated C++ classes that look something like this:

struct FooDataset
{
    typedef int DataType;
    typedef float ReturnType;

    // methods, other important stuff
};

struct BarDataset
{
    typedef long DataType;
    typedef double ReturnType;

    // methods, other important stuff
};

template <class Dataset>
class DataProcessor{

    DataProcessor(Dataset& input_data);

    typedef typename Dataset::DataType T;
    typedef typename Dataset::ReturnType R;

    T getDataItem();
    R computeSomething(); /* etc. */

    // do some other stuff that might involve T and/or R
};

Having typedef(s) internal to the struct gives me better encapsulation since I only need to pass a single template parameter (the Dataset class) rather than individually specifying the Dataset plus T, R, ... specific to that Dataset type.

I realise that it's not too difficult to find workarounds for this case - I'm mostly just interested in getting a definitive answer as to whether or not internal typedefs are currently possible in Cython.

like image 985
ali_m Avatar asked Feb 07 '15 13:02

ali_m


1 Answers

As far as I know this is not currently supported in Cython. But can't you just define it outside of the struct?

Cython is not currently designed as a replacement for C++, rather a way to speed up hot spots in python code. If you need something more involved just write it in C++ and expose python bindings.

like image 189
Alex Avatar answered Oct 20 '22 14:10

Alex