wrapping function-like macros with generic types

51 views
Skip to first unread message

mafiaem...@gmail.com

unread,
Dec 24, 2016, 12:08:45 PM12/24/16
to cython-users
If I have a function-like macro that can take a wide variety of types as 
parameters, defined either through C11 _Generic or preprocessor conditionals 
or other means, how can I wrap it in a type-agnostic manner?
Consider this sample which was not written for correctness:

from libc.stdlib cimport calloc
from libc.stdio cimport printf

cdef extern from *:
    # this type does not exist
    # trick cython into thinking it does
    struct T

    void stackdef """
#define stack_push(stack, item) (*stack++ = item)
#define stack_pop(stack) (*--stack)
#define ignore""" ()

    void stack_push(void *stack, T item)
    T stack_pop(void *stack)

cdef struct record:
    int val

cdef void main():
    stackdef()

    cdef:
        record *stack = <record *> calloc(3, sizeof(record))
        record r

    r.val = 1
    # cast to non-existant type struct T to appease cython's type checking
    stack_push(stack, <T> r)

    r.val = 2
    stack_push(stack, <T> r)

    r.val = 3
    stack_push(stack, <T> r)

    r = <record> stack_pop(stack)
    printf("Third record: %d\n", r.val)

    r = <record> stack_pop(stack)
    printf("Second record: %d\n", r.val)

    r = <record> stack_pop(stack)
    printf("First record: %d\n", r.val)

This sample works by accident, and only for structs. But what about ints, 
floats, etc? Really I just want to tell Cython pass a parameter as-is, no 
automatic conversion, type checking, etc. Something like an "any" or 
"pass-through" type but specifically for wrapped declarations. Or declare 
that function as a macro function which will do none of the previous.
I don't know how feasible that is.

mafiaem...@gmail.com

unread,
Dec 25, 2016, 10:53:24 AM12/25/16
to cython-users
Looks like I can abuse varargs for this, declaring stack_push like so: 
void stack_push(...)
I lose out on Cython checking I at least get the number of arguments right, 
and I tend to use wrapped external declarations as quick-references for type 
of parameters and their order so I lose that too but this is tenable.
Reply all
Reply to author
Forward
0 new messages