Pergunta

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?

Nenhuma solução correta

Outras dicas

I figured this out. My problem was I was doing this:

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

This doesn't work, because rv['val'] is a python object now, so you can't access the cdef attrs. You need to use an intermediate cdef, like this

cdef ExtensionType tmpvar
rv = {}
tmpvar = ExtensionType()
tmpvar.c_attr = val
rv['val'] = tmpvar
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top