c - 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。
解决方案
有一本名为C 接口和实现:创建可重用软件的技术的经典书籍,其中对同一件事进行了深入的讨论。如果我记得,它在第一章。
应该有2个解决方案:
- 将所有成员函数定义
createMyStruct
为宏(type)
。 - 使用
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 。
推荐阅读
- android - 如何以编程方式更改通知的默认应用程序设置,kotlin?
- blockchain - 为以太坊开发的智能合约也能用在币安智能链上?
- c# - 如何在 C# WPF 中创建一个可以与控件交互的完全自定义光标?
- linux - 使用 oci 堡垒服务连接到私有 kubernetes 集群时出错
- mysql - MySQL ...更新一个表,其中包含另一个表的值;多个条件
- ssl - SslHandler 的握手是否通过所有客户端/服务器管道处理程序?
- azure-functions - 多次调用 Azure 函数
- javascript - 想要从存在给定 accountId 的角色中获取数据。(Javascript, MongoDb)
- android-studio - 将 Unity Android 项目导入 Android Studio Wear OS 项目不让我点击完成按钮
- python - 如何在 Python 中处理循环依赖类