dimanche 31 mai 2020

How to write a platform independent wrapper function in C++

I am using snprintf to send the output to the buffer.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

void WrapperSprintf( char buffer, MAX_PATH, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf(buffer,MAX_PATH, sizeof(buffer), format,...);
#else
    snprintf(buffer,MAX_PATH, format, ...);
#endif
}

Calling WrapperSprintf function1:

char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime, MAX_PATH,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}

Calling WrapperSprintf function2:

void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath, MAX_PATH, "%ls",strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}

Aucun commentaire:

Enregistrer un commentaire