Cython-复制构造函数 [英] Cython - copy constructors

查看:63
本文介绍了Cython-复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要封装在Cython中的C库。我正在创建的一个类包含一个指向C结构的指针。我想编写一个复制构造函数,该函数将创建另一个指向相同C结构的Python对象,但由于无法将指针转换为python对象,因此遇到了麻烦。

I've got a C library that I'm trying to wrap in Cython. One of the classes I'm creating contains a pointer to a C structure. I'd like to write a copy constructor that would create a second Python object pointing to the same C structure, but I'm having trouble, as the pointer cannot be converted into a python object.

这是我想要的草图:

cdef class StructName:
     cdef c_libname.StructName* __structname

     def __cinit__(self, other = None):
         if not other:
             self.__structname = c_libname.constructStructName()
         elif type(other) is StructName:
             self.__structname = other.__structname

真正的问题是最后一行-似乎Cython无法从python方法中访问cdef字段。我尝试编写访问器方法,但结果相同。在这种情况下如何创建副本构造函数?

The real problem is that last line - it seems Cython can't access cdef fields from within a python method. I've tried writing an accessor method, with the same result. How can I create a copy constructor in this situation?

推荐答案

使用 cdef 类,将属性访问编译为C struct成员访问。因此,要访问对象 A cdef 成员,必须确保 A 。在 __ cinit __ 中,您没有告诉Cython另一个是 StructName 的实例。因此,Cython拒绝编译 other .__ structname 。要解决该问题,只需编写

When playing with cdef classes, attribute access are compiled to C struct member access. As a consequence, to access to a cdef member of an object A you have to be sure of the type of A. In __cinit__ you didn't tell Cython that other is an instance of StructName. Therefore Cython refuses to compile other.__structname. To fix the problem, just write

def __cinit__(self, StructName other = None):

注意:等效于 NULL ,因此被接受为 StructName

Note: None is equivalent to NULL and therefore is accepted as a StructName.

如果您想要更多的多态性,则必须依靠类型转换:

If you want more polymorphism then you have to rely on type casts:

 def __cinit__(self, other = None):
     cdef StructName ostr
     if not other:
         self.__structname = c_libname.constructStructName()
     elif type(other) is StructName:
         ostr = <StructName> other
         self.__structname = ostr.__structname

这篇关于Cython-复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆