首页 > 解决方案 > C 在函数原型中使用宏结构

问题描述

我正在使用宏在 C 中模拟模板。我想实现这样的目标:

// Struct.h
#define define_struct(type) \
  typedef struct MyStruct { \
    type value;             \
  }

struct MyStruct;
typedef struct MyStruct MyStruct;

MyStruct *createMyStruct();
// Struct.c
#include "Struct.h"
#include <stdlib.h>

MyStruct *createMyStruct() {
  MyStruct *str = malloc(sizeof(MyStruct));
  return str;
}

然后使用它:

#include "Struct.h"

define_struct(int);

int main() {
  MyStruct *str = createMyStruct();
}

但这不起作用,因为struct MyStruct;它是一个不完整的类型,malloc(MyStruct)对编译器没有意义。是否有可能做到这一点而没有错误?

PS我明白,为什么这不起作用,我绝对确定我永远不需要定义这个结构的2个实例,我不能使用C++,只能使用普通C。

标签: cstructmacros

解决方案


有一本名为C 接口和实现:创建可重用软件的技术的经典书籍,其中对同一件事进行了深入的讨论。如果我记得,它在第一章。

应该有2个解决方案:

  1. 将所有成员函数定义createMyStruct为宏(type)
  2. 使用impl指针,例如:
struct MyStruct {
    void *impl;

    /* stuff that store actual type of imple and something else */
    some_type_to_store_type actual_type;
};

MyStruct *createMyStruct(some_type_to_store_type actual_type) {
  MyStruct *str = malloc(sizeof(Mystruct));
       // wow! sizeof Mystruct is fixed now
  str->impl = make_impl(actual_type);
  return str;
}

此外,有一些库使用这种编码风格,但我不记得名字了。尝试C OOP在谷歌搜索,应该有一些材料,例如这个看起来不错:https ://www.state-machine.com/doc/AN_OOP_in_C.pdf 。


推荐阅读