Wednesday, July 11, 2012

C++ Runtime Dynamic Linking using Function Name Mangling

Disclaimer: This article is for Windows Developers working with DLL

Microsoft frequently releases new version of OS and Service Packs. Along with each release, they also ship New APIs. The new APIs can be an enchancement for already existing APIs (or) the APIs can do certain functions that are specific for any newly introduced technology.

The APIs will work only in latest OS. They won't be availble in previous versions of OS. The application developed in new OS wont run in older versions, also the new API cannot be used in older Windows Versions.

Developing Windows applications that use new APIs and work in latest and older versions of Windows can be done using the Microsoft's Run Time Dynmaic Linking concept.

Run Time Dynmaic Linking:

Verifying whether an API is present in kernel32.dll and then using it or ignoring it is called Run Time Dynmaic Linking. Please refer the article in this page: http://msdn.microsoft.com/en-us/library/ms810279.aspx

Sample Code:

The code illustrates whether RegCreateKeyExW is present in kernel32.dll or not.

#include <stdafx.h>
#include <stdlib.h>
#include <windows.h>
#include <Winreg.h>

#pragma comment(lib, "Advapi32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    LONG (__stdcall *regAPI)(HKEY, LPCTSTR, DWORD, LPTSTR, DWORD, REGSAM, LPSECURITY_ATTRIBUTES, PHKEY, LPDWORD);

    if (HINSTANCE hInst = LoadLibraryW(L"kernel32.dll"))
    {
        regAPI = (LONG (__stdcall *)(HKEY, LPCTSTR, DWORD, LPTSTR, DWORD, REGSAM, LPSECURITY_ATTRIBUTES, PHKEY, LPDWORD))GetProcAddress(hInst, "RegCreateKeyExW");
        if(regAPI != NULL)
        {
            // Do Registry creation operation
        }
        else
        {
            printf("\nRegCreateKeyExW is absent in this OS. Exiting!!\n");
        }
        FreeLibrary(hInst);
    }
    
    return 0;
}

No comments:

Post a Comment