[Pyrex] Return value problems

Georg Grabler ggrabler at gmail.com
Tue May 29 17:00:10 UTC 2007


Thank you Greg. That also is a very interesting piece. I'll try that
tonight, since it would save me some extra functions which do
basically the same thing.

I'll see how this behaves when returning pointers to structures
defined in an external library.

You guys are great, asking questions is also a way to learn ;).

Yours,
Georg

On 5/29/07, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Georg Grabler wrote:
>
> > cdef class config:
> >   ...
> >   cdef char* xyz
> >
> > cdef getXYZ(self)
> >   return self.xyz
>
> I'm assuming this is meant to be a method of class config
> (to work as a stand-alone function, a type declaration
> would be needed for the parameter).
>
> > if (config.getXYZ() == NULL):
>
> This test makes no sense. The way your getXYZ method
> is defined (whether the def or cdef version) it's returning
> a Python object, which will never be NULL.
>
> Moreover, if xyz is ever NULL, Python will crash trying
> to construct a Python string from it before even getting
> to your test.
>
> The way to proceed depends on whether getXYZ needs to be
> callable from Python. If it will only ever be called from
> Pyrex code, you could make it a C method that returns a
> char *, i.e.
>
>    cdef class config:
>      ...
>      cdef char *getXYZ(self):
>        return self.xyz
>
> Then you can do 'if foo.getXYZ() == NULL'. However, since
> you need to know that you have an object of class config
> before you can call the method, there's not much point in
> having the method rather than just accessing the xyz
> attribute directly.
>
> If the method needs to be callable from Python, you will
> need to declare it with def, and it will need to return a
> Python string. If xyz can be NULL, you will need to test
> for this and return something appropriate, e.g.
>
>    cdef class config:
>      ...
>      def getXYZ(self):
>        if self.xyz <> NULL:
>          return self.xyz
>        else:
>          return None
>
> Then you can do things like
>
>    if foo.getXYZ() is None:
>      ...
>
> --
> Greg
>



More information about the Pyrex mailing list