Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C macro get typeof argument

I am trying to write a macro to assist with object oriented programming in C. As I store the class information in a constant struct, I need to create a macro that does the following:

  • Take the type of the object (typeof the derefenced pointer)
  • Append _info to get the name of the desired classInfo struct
  • Take the address of that symbol so it can be passed to the function
  • Call the destroyObject function with a pointer to the class struct and the object itself

An example:

queue_t* p = NULL;
delete(p);

delete should expand to:

destroyObject(&(queue_t_info), p);

I tried using this macro, but I can't get to to work:

#define delete(X) (destroyObject(&(typeof(*X)##_info), X))

I'm having trouble with the typeof part to work correctly.

like image 533
charliehorse55 Avatar asked Jan 14 '23 02:01

charliehorse55


1 Answers

typeof isn't macro, it is language construction and it is expanded by compiler, not preprocessor. Since preprocessing goes before compilation, macro can't access typeof result.

Your delete(p) is expanded to: (destroyObject(&(typeof(*p)_info), p)). (You can see it by -E gcc flag)

like image 88
nmikhailov Avatar answered Jan 19 '23 10:01

nmikhailov