Avinash
Avinash

Reputation: 13267

C++ design pattern platform specific api

I am working on Windows. I have to see certain set of API's for Windows 2008 and above and different set of API's for other flavors of Windows. I want to know what is the best way to design such kind of stuff, so that my main driver code do not have #ifdef

For Example: In Windows 2008 We have API

EVT_HANDLE WINAPI EvtOpenLog(
  __in  EVT_HANDLE Session,
  __in  LPCWSTR Path,
  __in  DWORD Flags
);

and For Windows 2003 we have another API which does the same.

HANDLE OpenEventLog(
  __in  LPCTSTR lpUNCServerName,
  __in  LPCTSTR lpSourceName
);

What I am looking for is having some kind of wrapper API in my code which internally handles these calls.

Upvotes: 5

Views: 761

Answers (2)

Kevin Depue
Kevin Depue

Reputation: 415

One approach would be to have an interface in a header that doesn't change and to have separate .cpp's for each platform that you require. You then compile only the .cpp that you need for a given platform.

A second approach is to have a single base class interface that doesn't change and to have subclasses that modify code as necessary through virtual functions, but I don't recommend this approach.

Yet another approach would be to use something like the PIMPL (pointer to implementation) idiom. This approach will allow your header interface to never change and will also hide all platform-specific data in a private class implementation. Here's a semi-decent article on this design pattern.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206616

You can write an Platform Abstraction Layer, which will expose a common interface for all api types and for each port then you can implement the interface. You can provide the abstraction as an separate library for each port which ensures that your calling application remains the same only the library to be linked changes.

Upvotes: 6

Related Questions