C宏获取typeof参数 [英] C macro get typeof argument
问题描述
我正在尝试编写一个宏,以协助在C语言中进行面向对象的编程.由于我将类信息存储在恒定的结构中,因此我需要创建一个执行以下操作的宏:
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:
- 获取对象的类型(取消引用的指针的类型)
- 附加
_info
以获得所需的classInfo结构的名称 - 获取该符号的地址,以便可以将其传递给函数
- 使用指向类struct和对象本身的指针调用
destroyObject
函数
- 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
一个例子:
queue_t* p = NULL;
delete(p);
删除
应该扩展为:
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))
我无法正常使用typeof部件.
I'm having trouble with the typeof part to work correctly.
推荐答案
typeof
不是宏,它是语言构造,是由编译器而不是预处理器扩展的.由于预处理是在编译之前进行的,因此宏无法访问 typeof
结果.
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.
您的 delete(p)
扩展为:(destroyObject(&(typeof(* p)_info),p))
.(您可以通过 -E
gcc标志看到它)
Your delete(p)
is expanded to: (destroyObject(&(typeof(*p)_info), p))
. (You can see it by -E
gcc flag)
这篇关于C宏获取typeof参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!