Typedef 与平台抽象的容器结构?
我正在开发一个小型平台抽象层,打算将其用作未来项目的基础。最初,我是跟随SDL的思路,动态分配一个容器结构。
例如,在公共标头中:
typedef struct MY_MUTEX MY_MUTEX;
在特定于 Windows 的源文件中:
struct MY_MUTEX {
HANDLE handle;
};
MY_MUTEX *MY_CreateMutex() {
MY_MUTEX *m = malloc(sizeof(MY_MUTEX));
...
m->handle = CreateMutex(NULL, FALSE, NULL);
...
}
但后来我开始想知道是否可以完全放弃内存分配,而只使用 typedef
特定于平台的类型:
#ifdef _WIN32
typedef HANDLE MY_MUTEX;
#else
typedef pthread_mutex_t MY_MUTEX;
#endif
避免不必要的内存分配似乎是这样对我来说这是个好主意,但是这个简单的 typedef
方法会引入什么样的问题(如果有的话)?我会牺牲很多灵活性吗?
I'm working on a small platform abstraction layer that I intend to use as a base for future projects. Originally, I was following the lead of SDL and dynamically allocating a container structure.
For example, in the public header:
typedef struct MY_MUTEX MY_MUTEX;
In the Windows-specific source file:
struct MY_MUTEX {
HANDLE handle;
};
MY_MUTEX *MY_CreateMutex() {
MY_MUTEX *m = malloc(sizeof(MY_MUTEX));
...
m->handle = CreateMutex(NULL, FALSE, NULL);
...
}
But then I started wondering if I could ditch memory allocation altogether and just typedef
the platform-specific type:
#ifdef _WIN32
typedef HANDLE MY_MUTEX;
#else
typedef pthread_mutex_t MY_MUTEX;
#endif
Avoiding unnecessary memory allocations seems like a good idea to me, but what kind of problems (if any) would this simple typedef
method introduce? Would I be sacrificing a lot of flexibility?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 typedef、容器结构,甚至宏——任何一个都可以。即使是混合物也很好。重要的是,无论使用哪种底层实现,您的抽象在跨平台上的行为都是一致的——这可能会使某些选择不适合某些情况。
例如,使用简单的
typedef
来模拟 Unix 上的 Windows 事件对象可能不合理,因此您可以使用事件容器结构......但这不应该阻止您使用互斥体的typedef
,只要它足以满足通过抽象使用互斥体的方式。我确信有些人更愿意对整个 API 坚持一种方法,但只要抽象在一个平台到另一个平台上出现并表现一致,我认为就没有必要这样做。
基本上,选择适合每种情况的最轻的东西。
You can use
typedef
, a container structure, or even macros -- any of those are fine. Even a mixture is fine. The important thing is that your abstraction behaves consistently across platforms, no matter which underlying implementation is used -- and this may make some choices unsuitable for some cases.For example, it may not be reasonable to use a simple
typedef
to mimic a Windows Event object on Unix, so you might use a container struct for events... but that shouldn't stop you from using atypedef
for mutexes, as long as that's sufficient for the way mutexes will be used through your abstraction.I'm sure there are some who would prefer to stick to one approach for the whole API, but I don't see the need to as long as the abstraction appears and behaves consistently from one platform to another.
Basically, go with the lightest thing that works in each case.