[Pyrex] Segfault when trying to set attribute of another class

Armin Bauer armin.bauer at desscon.com
Sat Apr 10 13:10:13 CEST 2004


Thanks for your answer. The fixes you told me did not work correctly.
But they gave me a push in the right direction

On Mon, 2004-03-22 at 00:56, Greg Ewing wrote:
> Armin Bauer <armin.bauer at desscon.com>:
> 
> > cdef class CLASS2:
> > 	cdef STRUCT2 *_struct2
> > 	
> > 	def get_class1(self):
> > 		s = CLASS1()
> > 		s._set_struct1(<object>get_struct1_from_struct2(self._struct2))
> > 		print "test2"
> > 		return s
> 
> It looks like you're trying to smuggle a non-Python pointer into the
> _set_struct1 method by pretending it's a Python object. That won't
> work.
> 
> You should NEVER cast a pointer to a Python type unless it really and
> truly points to a Python object. Crashing and burning is guaranteed to
> result.
> 
> There are two things you could do here:
> 
> (1) Assign the pointer directly, not bothering with a _set_struct1
>     method.
> 
>   cdef class CLASS2:
>     ...
>     def get_class1(self):
>       cdef CLASS1 *s       # <--- note type declaration
I get a "Pointer base type cannot be a Python object" error here

>       s = CLASS1()
>       s._struct1 = get_struct1_from_struct2(self._struct2)
>       ...
> 

This approach worked when it is done like this:

cdef class CLASS2:
    ...
    def get_class1(self):
      cdef CLASS1 s       # <--- note the missing *
      s = CLASS1()
      s._struct1 = get_struct1_from_struct2(self._struct2)

But now i get "use of cast expressions as lvalues is deprecated"
warnings from the generated c file from lines like this with gcc 3.3.3:
((PyObject*)__pyx_v_s) = Py_None; Py_INCREF(((PyObject*)__pyx_v_s));

Switching to gcc 3.2 got rid of these messages.

> (2) If you particularly want to set it via an accessor method, use
>     a C method (introduced in Pyrex 0.9):
> 
>   cdef class CLASS1:
>     ...
>     # --- Note the following header ---
>     cdef void _set_struct1(self, STRUCT1 *s1):
>       self._struct1 = s1
> 
>   cdef class CLASS2:
>     ...
>     def get_class1(self):
>       cdef CLASS1 *s       # <--- note type declaration
this line also had to be changed to cdef CLASS1 s
but i also get the warnings here with the newest gcc

>       s = CLASS1()
>       s._set_struct1(get_struct1_from_struct2(self._struct2))
>       ...
> 
> Greg Ewing, Computer Science Dept, +--------------------------------------+
> University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
> Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
> greg at cosc.canterbury.ac.nz	   +--------------------------------------+
> 
> _______________________________________________
> Pyrex mailing list
> Pyrex at lists.copyleft.no
> http://lists.copyleft.no/mailman/listinfo/pyrex





More information about the Pyrex mailing list