On Fri, 05 Apr 2013 23:31:44 +0600, Sturla Molden <stu...@molden.no> wrote:

offsetof() is not supported by current Cython, and I have not found any
workaround (except hardcoding offsets for a specific architecture and
compiler, but this is obviously wrong).

offsetof() would certainly be very useful, but in the meantime
offsetof(Struct, field) can be replaced with:

     <Py_ssize_t>&(<Struct*>NULL).field

It's not ANSI C, but is portable enough.

This will dereference a NULL pointer.

Nope it won't. It is purely an address calculation. Works fine
in both msvc and gcc.
offsetof is a builtin in gcc, but msvc implements it as a macro
similar to the above.

Also, Py_ssize_t is not guaranteed to be long enough to store a pointer (but Py_intptr_t is). Use Py_intptr_t when you cast pointers to integers.

Thanks, Py_intptr_t is indeed more appropriate. I didn't know it existed.

Another option (for extern or public structs only) is to abuse
renaming:

     enum:
         Struct_offsetof_field1 "offsetof(Struct, field1)"

This will fail if "Struct" is name mangled by Cython. Basically it requires that it is defined outside of the Cython code, e.g. in a header file.

Please note "(for extern or public structs only)". These are not mangled.


Best regards,
Nikita Nemkin
_______________________________________________
cython-devel mailing list
cython-devel@python.org
http://mail.python.org/mailman/listinfo/cython-devel

Reply via email to