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 *'
解决方案
您第一次尝试 ( 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
推荐阅读
- sql - 来自 SQL / Impala 中脚本的 JOIN 查询
- bash - 只有一些并行步骤的作业数组和 shell 脚本
- objective-c - XPC 客户端等待服务加载
- c++ - 为什么 Glew 在 MacOS Catalina 中找不到 OpenGL 标头?
- linux - 每 5 分钟运行一次任务,但不要在星期一 9 到星期四下午 1 点之间运行
- java - int 无法转换为 2D 数组的 int[][] 错误
- laravel - CSRF 令牌与 laravel 和 pusher 不匹配
- c - 我们如何在c中调用汇编函数?
- kotlin - kotlin 循环遍历 2 个不同长度的列表
- monaco-editor - 在光标位置访问类型定义?