仅使用一个静态方法(没有构造函数)初始化类

时间:2019-03-10 09:09:08

标签: cython

MyClass.h(我正在尝试包装的C ++库)的样子

class MyClass {
public:
  static AnotherType func();

};

func()返回AnotherType的详细初始化,例如AnotherType(int a, int b)

如果我把它包起来:

cdef extern from 'MyClass.h':
  cdef cppclass MyClass:
    @staticmethod
    AnotherType func();

cdef extern from 'AnotherType.h':
  cdef cppclass AnotherType:
    AnotherType(int a, int b);

然后如何为func()分配内容?

如果我愿意

cdef AnotherType another = MyType.func()

我刚收到一条错误消息:

C++ class must have a nullary constructor to be stack allocated

(并且此类没有任何构造函数)。

如果我改为尝试将其分配给类中的指针(根据Cython关于无空构造函数的类的文档)

cdef class MyClassWrapper:
  cdef AnotherType* another
    def __cinit__(self):
      self.another = MyType.func()

我只收到错误消息

Cannot assign type 'AnotherType' to 'AnotherType *'

1 个答案:

答案 0 :(得分:1)

您第一次尝试(cdef AnotherType another = MyType.func())时遇到的问题是Cython生成如下代码:

AnotherType another{}; // no argument nullary constructor
another = MyType::func(); // copy assignment

因此,another必须是没有参数的可构造函数。这样做的原因是让您获得Python而不是C ++的作用域(即,如果在another语句中分配了if,则在整个函数中都可以访问它,而与C ++不同)。

您的第二种方法更接近于纠正。但是,您需要显式地使用copy或move构造函数:

self.another = new AnotherType(MyType.func())

您可能需要将AnotherType的副本构造函数告诉Cython(C ++隐式声明,但默认情况下Cython不知道):

cdef cppclass AnotherType:
    AnotherType(int a, int b);
    AnotherType(AnotherType&) # copy constructor
相关问题