Example: Explicitly Linking a File Conversion Function
Program 2-4 is an ASCII-to-Unicode file conversion program that calls the function Asc2Un (Program 2-5) to process the file using file I/O. Program 5-3 (Asc2UnMM) is an alternative function that uses memory mapping to perform exactly the same operation. The circumstances under which Asc2UnMM is faster were described earlier; essentially, the file system should be NTFS and the file should not be too large.Exercise 59 suggests that the DLL is determined on the basis of system and file characteristics. Also notice how the FARPROC address is cast to the appropriate function type using the required, but complex, C syntax.
Program 5-7. atouEL: File Conversion with Explicit Linking
/* Chapter 5. atou Explicit Link version. */
#include "EvryThng.h"
int _tmain (int argc, LPTSTR argv [])
{
/* Declare variable Asc2Un to be a function. */
BOOL (*Asc2Un)(LPCTSTR, LPCTSTR, BOOL);
DWORD LocFileIn, LocFileOut, LocDLL, DashI;
HINSTANCE hDLL;
FARPROC pA2U;
LocFileIn = Options (argc, argv, _T ("i"), &DashI, NULL);
LocFileOut = LocFileIn + 1;
LocDLL = LocFileOut + 1;
/* Test for existing file && DashI is omitted. */
/* Load the ASCII-to-Unicode function. */
hDLL = LoadLibrary (argv [LocDLL]);
if (hDLL == NULL)
ReportError (_T ("Failed loading DLL."), 1, TRUE);
/* Get the entry point address. */
pA2U = GetProcAddress (hDLL, "Asc2Un");
if (pA2U == NULL)
ReportError (_T ("Failed to find entry point."), 2, TRUE);
/* Cast the pointer. A typedef could be used here. */
Asc2Un = (BOOL (*)(LPCTSTR, LPCTSTR, BOOL)) pA2U;
/* Call the function. */
Asc2Un (argv [LocFileIn], argv [LocFileOut], FALSE);
FreeLibrary (hDLL);
return 0;
}
Building the Asc2Un DLLs
This program was tested with the two file conversion functions, which must be built as DLLs with different names but identical entry points. There is only one entry point in this case. The only significant change in the source code is the addition of a storage modifier, _declspec (dllexport), to export the function.