在Cython中是否可以使用C++风格的内部typedef

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

本文关键字:风格 内部 typedef C++ Cython 是否 可以使      更新时间:2023-10-16

在C++中,可以声明属于类或结构的类型别名:

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

有没有办法在Cython做同样的事情?我尝试过最明显的方法:

cdef struct Foo:
    ctypedef int DataType

但这不起作用:

Error compiling Cython file:
------------------------------------------------------------
...
# distutils: language=c++
cdef struct Foo:
    ctypedef int DataType
   ^
------------------------------------------------------------
internal_typedefs_example.pyx:4:4: Expected an identifier, found 'ctypedef'

这只是Cython的一个基本限制(我使用的是v0.21.2),还是有一个变通方法?


为什么要麻烦内部typedef?有几个普遍的原因——之前的SO问题涵盖了其中的一些原因。

我感兴趣的具体案例是包装一组模板化的C++类,它们看起来像这样:

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
};

在结构内部设置typedef可以更好地封装,因为我只需要传递一个模板参数(Dataset类),而不需要单独指定特定于该Dataset类型的DatasetT, R, ...

我意识到,为这种情况找到解决办法并不太难——我最感兴趣的只是得到一个明确的答案,即Cython目前是否可以使用内部typedef。

据我所知,Cython目前不支持这一功能。但是你不能在结构之外定义它吗?

Cython目前并不是作为C++的替代品设计的,而是一种加速python代码热点的方法。如果您需要更多相关内容,只需用C++编写并公开python绑定即可。

在C++中,struct是声明类的关键字。因此,内部typedef可以在Cython中声明为:

cdef cppclass Foo:
    ctypedef int DataType