开发者

Typedef vs. container structure for platform abstraction?

开发者 https://www.devze.com 2023-04-11 03:42 出处:网络
I\'m working on a small platform abstraction layer that I intend to use as a base for future projects. Originally, I was foll开发者_Go百科owing the lead of SDL and dynamically allocating a container s

I'm working on a small platform abstraction layer that I intend to use as a base for future projects. Originally, I was foll开发者_Go百科owing 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?


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 a typedef 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消