It seems that when defining bindings to c functions that return
structures that Cython automagically converts them to Python
dictionaries.
I am now having trouble getting this to happen with a structure that
has a union inside of it.
Is this something that is not supported by Cython?
I had this working (being able to return the structure from a .pyx
function) without the union, then when I added the union to the
structure I get the message "Cannot convert 'tcurts_t' to Python
object"
Suggestions?
=== PXD ===
cdef extern from "test.h"
cdef enum value_type_e:
VALUE_STRING
VALUE_INTEGER
VALUE_DOUBLE
ctypedef value_type_e value_type_t
ctypedef union val_union:
char vstr[80]
int vint
double vdouble
# tcurts is struct backwards ;-)
cdef struct tcurts_s:
int a
int b
double c
double d
value_type_t val_type
val_union value
ctypedef tcurts_s tcurts_t
=== PYX ===
cimport cericslib
def gimmie_a_struct(int a, int b, double c, double d, char* s):
cdef cericslib.tcurts_t ret
ret = cericslib.gimmie_a_struct(a, b, c, d, s)
return ret
True, though this may change in the future. Mostly it's to be able to
do, e.g., "print my_struct_var."
> I am now having trouble getting this to happen with a structure that
> has a union inside of it.
> Is this something that is not supported by Cython?
Cython doesn't have a way to tell which of its members are valid and
which are not. I suppose it could just try to represent all of them...
> I had this working (being able to return the structure from a .pyx
> function) without the union, then when I added the union to the
> structure I get the message "Cannot convert 'tcurts_t' to Python
> object"
>
> Suggestions?
Write an actual struct -> object converter function.
I now understand the technical reasons not to represent them all.
If you had a union of an int and a char* and the int was valid, then
de-referencing the int could segfault.
A possible solution would be to return an object which lazily gets
structure members at run time.
If it is done lazily then segfaults would be avoided as long as the
Python code doesn't reference the invalid pointer.
Doing this you would lose the ability to print.
Just thinking out loud.
~Eric
That'll give you more control in the future as well.
> I now understand the technical reasons not to represent them all.
> If you had a union of an int and a char* and the int was valid, then
> de-referencing the int could segfault.
>
> A possible solution would be to return an object which lazily gets
> structure members at run time.
> If it is done lazily then segfaults would be avoided as long as the
> Python code doesn't reference the invalid pointer.
> Doing this you would lose the ability to print.
>
> Just thinking out loud.
There's actually though of doing something similar to this--one could
declare a struct/union "public" and Cython would create a shadow class
to pass to/from Python space. Attributes would be lazily converted.