2

I've got a Pyrex extension type like this:

cdef extern from "some_include.h":
  ctypedef struct AThing:
    ...

It is wrapped by a Pythoninc extension type:

cdef class Foo:
  cdef AThing c_val
  def __init__(self, somestring):
    self.c_val = from_string(somestring)

I would like to be able to create instances of this extension type from within Pyrex code elsewhere, using the existing C value, like so:

cdef some_func(avalue):
  cdef AThing val
  ...
  val = some_func()
  a_dict['foo'] = Foo()
  a_dict['foo'].c_val = val

...but this results in "Cannot convert 'AThing' to Python object". What's the general technique to create a Pyrex extension type that can be initialised from both Python and C?

4

1 回答 1

2

我想通了。我的问题是我正在这样做:

rv = {}
rv['val'] = ExtensionType()
rv['val'].c_attr = val

这不起作用,因为 rv['val'] 现在是一个 python 对象,所以你不能访问 cdef attrs。你需要使用中间的 cdef,像这样

cdef ExtensionType tmpvar
rv = {}
tmpvar = ExtensionType()
tmpvar.c_attr = val
rv['val'] = tmpvar
于 2012-11-21T13:34:39.183 回答