首页 > 解决方案 > 仅使用一个静态方法初始化类(无构造函数)

问题描述

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 *'

标签: cython

解决方案


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

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

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

你的第二种方法更接近正确。但是,您需要显式使用复制或移动构造函数:

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

您可能需要告诉 Cython 的复制构造函数AnotherType(这是由 C++ 隐式声明的,但 Cython 默认不知道):

cdef cppclass AnotherType:
    AnotherType(int a, int b);
    AnotherType(AnotherType&) # copy constructor

推荐阅读