[Cython] Syntax for writing C macros in a Cython .pxd
Stefan Behnel
stefan_ml at behnel.de
Fri Mar 21 19:24:56 CET 2008
Hi,
Martin C. Martin to-posted:
> Stefan Behnel wrote:
>> since William brought up this topic lately, I think there are a couple
>> of very valid cases where you want to define a macro in C and use it as a
>> function in Cython.
>>
>> I think this is so common that it would help if you could write inline
>> C code in a .pxd file and have it written into your generated C file
>> automatically. I could imagine a syntax like this:
>>
>> # macros.pxd
>> MACROS = """
>> #define _isString(obj) (PyString_CheckExact(obj) || \
>> PyUnicode_CheckExact(obj) || \
>> PyObject_TypeCheck(obj,
>> &PyBaseString_Type))
>>
>> #define _fqtypename(o) (((PyTypeObject*)o)->ob_type->tp_name)
>> """
>>
>> cdef inline from MACROS:
>> cdef int _isString(object obj)
>> cdef char* _fqtypename(object t)
>
> Macros in C have a lot of problems, so I think it's best to avoid them
> whenever possible. In particular:
>
> - The symbols they define don't show up in the debugger, memory
> profiler, or other tools.
Well, in most cases macros are rather short code snippets, not function
replacing code blocks. So I don't care about their symbols.
> - They work at the textual level, so it's easy to get incorrect
> behaviour if you forget to add extra parenthesis that aren't needed in
> normal C.
> - When using them to define an inline "function," they can't always be
> used all places a function can.
Sure, that's why you have to take care when you use them. In my first
sentence, I said "I think there are a couple of very valid cases", I think
that makes the focus clear.
> In your example:
>
> #define _fqtypename(o) (((PyTypeObject*)o)->ob_type->tp_name)
>
> _fqtypename(a + b) expands to:
>
> (((PyTypeObject*)a + b)->ob_type->tp_name)
And that's definitely not a valid use case of _fqtypename().
> If you want an inline function, why not just declare it inline?
Because for small code snippets that exist solely for performance reasons, the
overhead of a function defined in Cython may be too high.
> The use cases discussed on the list recently were to get around the fact
> that Cython doesn't know all that much about C or C++. Why not just
> teach it more?
Does that imply a 'real' syntax for C macros? I would deny the need. As you
noted, macros are defined at the text level.
Stefan
More information about the Cython-dev
mailing list