ctypesmacrospolymorphism

String manipulation macro: expected specifier-qualifier-list before ‘,’ token


I am trying to write a macro which will automate definition of polymorphic types achived by composition and function pointers.

I don't really know a lot about macro string manipulation. This is how I imagine the macro definition:

#define INSTANCE(ret, name, ...) ret (*name)(__VA_ARGS__);
#define TYPE(name, ...) typedef struct { Object base; __VA_ARGS__ } name

It may be used like following:

TYPE(A,
     INSTANCE(void, print_name, void),
     INSTANCE(void, set_id, char *, id)
);

And generated structure, in this example, should be:

typedef struct {
    Object base;
    void (*print_name)(void);
    void (*set_id)(char *);
} A;

In my implementation compiler returns error:

main.c:14:38: error: expected specifier-qualifier-list before ‘,’ token
   14 |      INSTANCE(void, print_name, void),
      |                                      ^

Did it mean that "arguments to function pointer evaluation" fails? What have I done wrong?


Solution

  • As already stated, you have too many commas in your source code. So either remove them manually or modify your macros to do it for you:

    #define REMOVECOMMA2(\
        a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,...) \
        a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 
    #define REMOVECOMMA(...) REMOVECOMMA2(__VA_ARGS__,,,,,,,,,,,,,,,,,,,,)
    
    #define INSTANCE(ret, name, ...) ret (*name)(REMOVECOMMA(__VA_ARGS__));
    #define TYPE(name, ...) typedef struct { Object base; REMOVECOMMA(__VA_ARGS__) } name
    
    TYPE(A,
        INSTANCE(void, print_name, void),
        INSTANCE(void, set_id, char *, id)
    );
    

    Please note that the macros can only remove a limited numbers of commas (in above example: 19)