| Main |Site Index |Download |Disclaimer |Privacy |


 

 

 

 

 

 

WINDOWS DLL: A SUPPLEMENTARY NOTE

 

 

 

 

 

 

 

 

 

 

 

 

 

 

This supplementary notes contain Dynamic-LinkLibrary (DLL) related Win32 functions used in program examples of theDLL part 1 andDLL part 2 tutorials or wherever applicable. To learn about functionyou can jump toC &C++ functions tutorials.

 

The Page Index

  1. DllMain()

  2. LoadLibrary()

  3. GetProcAddress()

  4. FreeLibrary()

  5. CreateFileMapping()

  6. MapViewOfFile()

  7. memset(), wmemset()

  8. UnmapViewOfFile()

 

The DllMain()

 

Ifyou already gone through this C/C++ tutorial from the beginning tillthis one, there are many mainfunctions that have been introduced.  They are:

 

  1. Standard main()as discussed in main() and command line argument.

  2. wmain()for wide character/Unicode discussed inUnicode & Multibyte part 1 and used inUnicode & Multibyte part 2.

  3. Dllmain()function for DLL program, discussed in this Module.

  4. mainfunction for Windows service program, discussed inWindows Services main function.

  5. Other mainfunction that you will find in MFC programs.

 

Item

Description

Function

DllMain().

Use

Is an optional entry point intoa dynamic-link library (DLL). If the function is used, itis called by the system when processes and threads are initializedand terminated, or upon calls to the LoadLibrary()and FreeLibrary()functions. DllMain()is a placeholder for the library-defined function name.You must specify the actual name you use when you buildyour DLL. For more information, see the documentation includedwith your development tools.

Prototype

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason,LPVOID lpvReserved);

Parameters

See below.

Return value

When the system calls theDllMain()function with the DLL_PROCESS_ATTACHvalue, the function returns TRUE if it succeeds or FALSEif initialization fails. If the return value is FALSE whenDllMain()is called because the process uses the LoadLibrary()function, LoadLibrary()returns NULL. The system immediately calls your entry-pointfunction with DLL_PROCESS_DETACHand unloads the DLL. If the return value is FALSE whenDllMain()is called during process initialization, the process terminateswith an error. To get extended error information, callGetLastError().When the system calls the DllMain()function with any value other than DLL_PROCESS_ATTACH,the return value is ignored.

Include file

-

Remark

See below.

 

Table 1.

 

Parameters

 

hinstDLL - [in] Handle to the DLL module. The valueis the base address of the DLL. The HINSTANCEof a DLL is the same as the HMODULE of the DLL, sohinstDLL can be used in callsto functions that require a module handle.

fdwReason - [in] Indicates why the DLL entry-point functionis being called. This parameter can be one of the following values.

 

Value

Meaning

DLL_PROCESS_ATTACH

The DLL is being loaded into the virtualaddress space of the current process as a result of the processstarting up or as a result of a call to LoadLibrary. DLLs can usethis opportunity to initialize any instance data or to use theTlsAlloc()function to allocate a thread local storage (TLS) index.

DLL_THREAD_ATTACH

The current process is creating a newthread. When this occurs, the system calls the entry-point functionof all DLLs currently attached to the process. The call is madein the context of the new thread. DLLs can use this opportunityto initialize a TLS slot for the thread. A thread calling the DLLentry-point function with DLL_PROCESS_ATTACHdoes not call the DLL entry-point function with DLL_THREAD_ATTACH.

Note that a DLL's entry-point functionis called with this value only by threads created after the DLLis loaded by the process. When a DLL is loaded using LoadLibrary(),existing threads do not call the entry-point function of the newlyloaded DLL.

DLL_THREAD_DETACH

A thread is exiting cleanly. If theDLL has stored a pointer to allocated memory in a TLS slot, it shoulduse this opportunity to free the memory. The system calls the entry-pointfunction of all currently loaded DLLs with this value. The callis made in the context of the exiting thread.

DLL_PROCESS_DETACH

The DLL is being unloaded from the virtualaddress space of the calling process as a result of unsuccessfullyloading the DLL, termination of the process, or a call to FreeLibrary().The DLL can use this opportunity to call the TlsFree() function to free any TLS indices allocatedby using TlsAlloc()and to free any thread local data.

Note that the thread that receives theDLL_PROCESS_DETACHnotification is not necessarily the same thread that received theDLL_PROCESS_ATTACHnotification.

 

Table 2.

 

lpvReserved -[in] If fdwReasonis DLL_PROCESS_ATTACH,lpvReserved is NULL for dynamicloads and non-NULL for static loads.

If fdwReasonis DLL_PROCESS_DETACH,lpvReserved is NULL if DllMain()has been called by using FreeLibrary() and non-NULL ifDllMain() has been called duringprocess termination.

 

Some Remarks

 

During initialprocess startup or after a call to LoadLibrary(),the system scans the list of loaded DLLs for the process. For each DLL thathas not already been called with the DLL_PROCESS_ATTACHvalue, the system calls the DLL's entry-point function. This call is made inthe context of the thread that caused the process address space to change, suchas the primary thread of the process or the thread that called LoadLibrary().Access to the entry point is serialized by the system on a process-wide basis.There are cases in which the entry-point function is called for a terminatingthread even if the entry-point function was never called with DLL_THREAD_ATTACHfor the thread:

  1. The thread was the initial thread in the process,so the system called the entry-point function with the DLL_PROCESS_ATTACHvalue.

  2. The thread was already running when a call tothe LoadLibrary() function was made, so the system never called the entry-pointfunction for it.

 

When a DLLis unloaded from a process as a result of an unsuccessful load of the DLL, terminationof the process, or a call to FreeLibrary(),the system does not call the DLL's entry-point function with the DLL_THREAD_DETACHvalue for the individual threads of the process. The DLL is only sent aDLL_PROCESS_DETACH notification. DLLs can takethis opportunity to clean up all resources for all threads known to the DLL.However, if the DLL does not successfully complete a DLL_PROCESS_ATTACHnotification, the DLL does not receive either a DLL_THREAD_DETACHor DLL_PROCESS_DETACHnotification. If you terminate a process by calling TerminateProcess()or TerminateJobObject(),the DLLs of that process do not receive DLL_PROCESS_DETACHnotifications. If you terminate a thread by calling TerminateThread(),the DLLs of that thread do not receive DLL_THREAD_DETACHnotifications. The entry-point function should perform only simple initializationor termination tasks. It must not call the LoadLibrary()or LoadLibraryEx()function (or a function that calls these functions), because this may createdependency loops in the DLL load order. This can result in a DLL being usedbefore the system has executed its initialization code. Similarly, the entry-pointfunction must not call the FreeLibrary()function (or a function that calls FreeLibrary()),because this can result in a DLL being used after the system has executed itstermination code.

It is safeto call other functions in Kernel32.dll, becausethis DLL is guaranteed to be loaded in the process address space when the entry-pointfunction is called. It is common for the entry-point function to create synchronizationobjects such as critical sections and mutexes, and use TLS. Do not call theregistry functions, because they are located in Advapi32.dll.If you are dynamically linking with the C run-time library, do not callmalloc(); instead, call HeapAlloc().Calling imported functions other than those located in Kernel32.dllmay result in problems that are difficult to diagnose. For example, callingUser, Shell, and COM functions can cause access violation errors, because somefunctions in their DLLs call LoadLibrary()to load other system components. Conversely, calling those functions duringtermination can cause access violation errors because the corresponding componentmay already have been unloaded or uninitialized. Because DLL notifications areserialized, entry-point functions should not attempt to communicate with otherthreads or processes. Deadlocks may occur as a result. Note:  To providemore complex initialization, create an initialization routine for the DLL. Youcan require applications to call the initialization routine before calling anyother routines in the DLL. Otherwise, you can have the initialization routinecreate a named mutex, and have each routine in the DLL call the initializationroutine if the mutex does not exist. Be sure to use a unique mutex name foreach process that loads the DLL.

 

LoadLibrary()

 

Item

Description

Function

LoadLibrary().

Use

Maps the specified executable moduleinto the address space of the calling process. For additional loadoptions, use the LoadLibraryEx()function.

Prototype

HMODULELoadLibrary(LPCTSTR lpFileName);

Parameters

lpFileName- [in] Pointer to a null-terminatedstring that names the executable module (either a .dllor .exefile). The name specified is the file name of the module and isnot related to the name stored in the library module itself, asspecified by the LIBRARYkeyword in the module-definition (.def)file.

If the string specifies a path but thefile does not exist in the specified directory, the function fails.When specifying a path, be sure to use backslashes (\),not forward slashes (/).

If the string does not specify a path,the function uses a standard search strategy to find the file. Seethe Remarks for more information.

Return value

If the function succeeds, the returnvalue is a handle to the module. If the function fails, the returnvalue is NULL. To get extended error information, call GetLastError().

For Windows Me/98/95:  If you areusing LoadLibrary()to load a module that contains a resource whose numeric identifieris greater than 0x7FFF,LoadLibrary()fails. If you are attempting to load a 16-bit DLL directly from32-bit code, LoadLibrary()fails. If you are attempting to load a DLL whose subsystem versionis greater than 4.0, LoadLibrary()fails. If your DllMain()function tries to call the Unicode version of a function, LoadLibrary()fails.

Include file

<windows.h>

Remark

Implemented as Unicode and ANSI versions.Note that Unicode support on Windows Me/98/95 requires MicrosoftLayer for Unicode. More remarks below.

 

Table 3.

 

Some Remarks

 

To enableor disable error messages displayed by the loader during DLL loads, use theSetErrorMode()function. LoadLibrary()can be used to map a DLL module and return a handle that can be used inGetProcAddress() to get the address of a DLLfunction. LoadLibrary()can also be used to map other executable modules. For example, the functioncan specify an .exefile to get a handle that can be used in FindResource()or LoadResource().However, do not use LoadLibrary()to run an .exefile, use the CreateProcess()function.

If the moduleis a DLL not already mapped for the calling process, the system calls the DLL'sDllMain()function with the DLL_PROCESS_ATTACHvalue. If the DLL's entry-point function does not return TRUE, LoadLibrary()fails and returns NULL. The system immediately calls your entry-point functionwith DLL_PROCESS_DETACHand unloads the DLL. It is not safe to call LoadLibrary()from DllMain().Module handles are not global or inheritable. A call to LoadLibrary()by one process does not produce a handle that another process can use. For example, in calling GetProcAddress().The other process must make its own call to LoadLibrary()for the module before calling GetProcAddress().If no file name extension is specified in the lpFileNameparameter, the default library extension .dllis appended. However, the file name string can include a trailing point character(.)to indicate that the module name has no extension. When no path is specified,the function searches for loaded modules whose base name matches the base nameof the module to be loaded. If the name matches, the load succeeds. Otherwise,the function searches for the file in the following sequence:

 

  1. Thedirectory from which the application loaded.

  2. Thecurrent directory.

  3. Thesystem directory. Use the GetSystemDirectory()function to get the path of this directory.

  4. The16-bit system directory. There is no function that obtains the path of thisdirectory, but it is searched. Windows Me/98/95:  This directory doesnot exist.

  5. TheWindows directory. Use the GetWindowsDirectory()function to get the path of this directory.

  6. Thedirectories that are listed in the PATHenvironment variable.

 

WindowsServer 2003, Windows XP SP1:  The default value of HKLM\System\CurrentControlSet\Control\SessionManager\SafeDllSearchModeis 1 (current directory is searched after the system and Windows directories).Windows XP:  If HKLM\System\CurrentControlSet\Control\SessionManager\SafeDllSearchModeis 1, the current directory is searched after the system and Windowsdirectories, but before the directories in the PATHenvironment variable. The default value is 0 (current directory is searchedbefore the system and Windows directories).

Thefirst directory searched is the one directory containing the image fileused to create the calling process. Doing this allows private dynamic-linklibrary (DLL) files associated with a process to be found without addingthe process's installed directory to the PATHenvironment variable. The search path can be altered using theSetDllDirectory()function. This solution is recommended instead of using SetCurrentDirectory()or hard-coding the full path to the DLL.

Ifa path is specified and there is a redirection file for the application, thefunction searches for the module in the application's directory. If the moduleexists in the application's directory, the LoadLibrary()function ignores the specified path and loads the module from the application'sdirectory. If the module does not exist in the application's directory,LoadLibrary() loads the modulefrom the specified directory. The Visual C++ compiler supports a syntax thatenables you to declare thread-local variables: _declspec(thread).If you use this syntax in a DLL, you will not be able to load the DLL explicitlyusing LoadLibrary()or LoadLibraryEx().If your DLL will be loaded explicitly, you must use the thread local storagefunctions instead of _declspec(thread).Windows Me/98/95:  LoadLibraryW()is supported by the Microsoft Layer for Unicode. To use this, you must add certainfiles to your application, as outlined in Microsoft Layer for Unicode on WindowsMe/98/95 Systems.

 

GetProcAddress()

 

Item

Description

Function

GetProcAddress().

Use

Retrieves the address of an exportedfunction or variable from the specified dynamic-link library (DLL).

Prototype

FARPROCGetProcAddress(HMODULE hModule, LPCSTR lpProcName);

Parameters

hModule- [in] Handle to the DLLmodule that contains the function or variable. The LoadLibrary()or GetModuleHandle()function returns this handle.

lpProcName- [in] Pointer to a null-terminatedstring that specifies the function or variable name, or the function'sordinal value. If this parameter is an ordinal value, it must bein the low-order word; the high-order word must be zero.

Return value

If the function succeeds, the returnvalue is the address of the exported function or variable. If thefunction fails, the return value is NULL. To get extended errorinformation, call GetLastError().

Include file

<windows.h>

Remark

The spelling and case of a functionname pointed to by lpProcNamemust be identical to that in the EXPORTSstatement of the source DLL's module-definition (.def)file. The exported names of functions may differ from the namesyou use when calling these functions in your code. This differenceis hidden by macros used in the SDK header files.

The lpProcNameparameter can identify the DLL function by specifying an ordinalvalue associated with the function in the EXPORTSstatement. GetProcAddress()verifies that the specified ordinal is in the range 1 through thehighest ordinal value exported in the .deffile. The function then uses the ordinal as an index to read thefunction's address from a function table. If the .deffile does not number the functions consecutively from 1 to N (whereN is the number of exported functions), an error can occur whereGetProcAddress()returns an invalid, non-NULL address, even though there is no functionwith the specified ordinal.

In cases where the function may notexist, the function should be specified by name rather than by ordinalvalue.

 

Table 4.

 

FreeLibrary()

 

Item

Description

Function

FreeLibrary().

Use

Decrements the reference count of theloaded dynamic-link library (DLL). When the reference count reacheszero, the module is unmapped from the address space of the callingprocess and the handle is no longer valid.

Prototype

BOOL FreeLibrary(HMODULEhModule);

Parameters

hModule- [in] Handle to the loadedDLL module. The LoadLibrary()or GetModuleHandle()function returns this handle.

Return value

If the function succeeds, the returnvalue is nonzero. If the function fails, the return value is zero.To get extended error information, call GetLastError().

Include file

<windows.h>

Remark

Each process maintains a reference countfor each loaded library module. This reference count is incrementedeach time LoadLibrary()is called and is decremented each time FreeLibrary()is called. A DLL module loaded at process initialization due toload-time dynamic linking has a reference count of one. This countis incremented if the same module is loaded by a call to LoadLibrary().Before unmapping a library module, the system enables the DLL todetach from the process by calling the DLL's DllMain()function, if it has one, with the DLL_PROCESS_DETACHvalue. Doing so gives the DLL an opportunity to clean up resourcesallocated on behalf of the current process. After the entry-pointfunction returns, the library module is removed from the addressspace of the current process. It is not safe to call FreeLibrary()from DllMain().Calling FreeLibrary()does not affect other processes using the same library module.

 

Table 5.

 

CreateFileMapping()

 

Item

Description

Function

CreateFileMapping().

Use

Creates or opens a named or unnamedfile mapping object for the specified file.

Prototype

HANDLECreateFileMapping( HANDLE hFile, LPSECURITY_ATTRIBUTES lpAttributes,DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow,LPCTSTR lpName);

Parameters

See below.

Return value

If the function succeeds, the returnvalue is a handle to the file mapping object. If the object existedbefore the function call, the function returns a handle to the existingobject (with its current size, not the specified size) andGetLastError()returns ERROR_ALREADY_EXISTS.If the function fails, the return value is NULL. To get extendederror information, call GetLastError().

Include file

<windows.h>

Remark

Implemented as Unicode and ANSI versions.Note that Unicode support on Windows Me/98/95 requires MicrosoftLayer for Unicode. More remarks below.

 

Table 6.

 

Parameters

 

hFile - [in] Handle to the file from which to createa mapping object. The file must be opened with access rights compatible withthe protection flags specified by the flProtectparameter. It is recommended, though not required, that files you intend tomap be opened for exclusive access. If hFileis INVALID_HANDLE_VALUE,the calling process must also specify a mapping object size in the dwMaximumSizeHighand dwMaximumSizeLowparameters. In this case, CreateFileMapping()creates a file mapping object of the specified size backed by the operating-systempaging file rather than by a named file in the file system. The file mappingobject can be shared through duplication, through inheritance, or by name. Theinitial contents of the pages in the file mapping object are zero.

lpAttributes -[in] Pointer to a SECURITY_ATTRIBUTESstructure that determines whether the returned handle can be inherited by childprocesses. If lpAttributesis NULL, the handle cannot be inherited. The lpSecurityDescriptormember of the structure specifies a security descriptor for the new file mappingobject. If lpAttributesis NULL, the file mapping object gets a default security descriptor. The ACLsin the default security descriptor for a file mapping object come from the primaryor impersonation token of the creator. Note that doing this involves potentialsecurity risks. To avoid these risks, use a valid SECURITY_ATTRIBUTESstructure.

flProtect - [in] Protection desired for the file view,when the file is mapped. This parameter can be one of the following values.

 

Value

Meaning

PAGE_READONLY

Gives read-only access to the committedregion of pages. An attempt to write to or execute the committedregion results in an access violation. The file specified by thehFileparameter must have been created with the GENERIC_READaccess right.

PAGE_READWRITE

Gives read/write access to the committedregion of pages. The file specified by hFilemust have been created with the GENERIC_READand GENERIC_WRITEaccess rights.

PAGE_WRITECOPY

Gives copy-on-write access to the committedregion of pages. The files specified by the hFileparameter must have been created with the GENERIC_READand GENERIC_WRITE access rights.

 

Table 7.

 

In addition,an application can specify certain section attributes by combining (using thebitwise OR operator) one or more of the following section attribute values withone of the preceding page protection values.

 

Value

Meaning

SEC_COMMIT

Allocates physical storage in memoryor in the paging file on disk for all pages of a section. This isthe default setting.

SEC_IMAGE

The file specified for a section's filemapping is an executable image file. Because the mapping informationand file protection are taken from the image file, no other attributesare valid with SEC_IMAGE. For Windows Me/98/95:  This flag is not supported.

SEC_NOCACHE

All pages of a section are to be setas non-cacheable. Applications should not use this flag except whenexplicitly required for a device. Using the interlocked functionswith memory mapped by a SEC_NOCACHEsection can result in a STATUS_ILLEGAL_INSTRUCTIONexception. Note that SEC_NOCACHErequires either the SEC_RESERVEor SEC_COMMITto also be set. For Windows Me/98/95:  This flag is not supported.

SEC_RESERVE

Reserves all pages of a section withoutallocating physical storage. The reserved range of pages cannotbe used by any other allocation operations until it is released.Reserved pages can be committed in subsequent calls to theVirtualAlloc()function. This attribute is valid only if the hFileparameter is INVALID_HANDLE_VALUE;that is, a file mapping object backed by the operating system pagingfile.

 

Table 8.

 

dwMaximumSizeHigh- [in] High-order DWORD of themaximum size of the file mapping object.

dwMaximumSizeLow -[in] Low-order DWORDof the maximum size of the file mapping object. If this parameter and dwMaximumSizeHighare zero, the maximum size of the file mapping object is equal to the currentsize of the file identified by hFile.

An attemptto map a file with a length of zero in this manner fails with an error codeof ERROR_FILE_INVALID.Applications should test for files with a length of zero and reject such files.

lpName - [in] Pointer to a null-terminated stringspecifying the name of the mapping object. If this parameter matches the nameof an existing named mapping object, the function requests access to the mappingobject with the protection specified by flProtect.If this parameter is NULL, the mapping object is created without a name. IflpNamematches the name of an existing event, semaphore, mutex, waitable timer, orjob object, the function fails and the GetLastError()function returns ERROR_INVALID_HANDLE.This occurs because these objects share the same name space.

TerminalServices:  The name can have a "Global\"or "Local\"prefix to explicitly create the object in the global or session name space.The remainder of the name can contain any character except the backslash character(\).

Windows XPHome Edition:  Fast user switching is implemented using Terminal Servicessessions. The first user to log on uses session 0, the next user to log on usessession 1, and so on. Kernel object names must follow the guidelines outlinedfor Terminal Services so that applications can support multiple users. Windows2000:  If Terminal Services is not running, the "Global\"and "Local\"prefixes are ignored. The remainder of the name can contain any character exceptthe backslash character. Windows NT:  The name can contain any characterexcept the backslash character. Windows Me/98/95:  The name can containany character except the backslash character. The empty string ("") is a validobject name.

 

Some Notes

 

After a filemapping object has been created, the size of the file must not exceed the sizeof the file mapping object; if it does, not all of the file's contents willbe available for sharing. If an application specifies a size for the file mappingobject that is larger than the size of the actual named file on disk, the fileon disk is grown to match the specified size of the file mapping object. Ifthe file cannot be grown, this results in a failure to create the file mappingobject. GetLastError()will return ERROR_DISK_FULL.

The handlethat CreateFileMapping()returns has full access to the new file mapping object. It can be used withany function that requires a handle to a file mapping object. File mapping objectscan be shared either through process creation, through handle duplication, orby name.

Windows Me/98/95: File handles that have been used to create file mapping objects must not beused in subsequent calls to file I/O functions, such as ReadFile()and WriteFile().In general, if a file handle has been used in a successful call to theCreateFileMapping() function,do not use that handle unless you first close the corresponding file mappingobject. Creating a file mapping object creates the potential for mapping a viewof the file but does not map the view. The MapViewOfFile()and MapViewOfFileEx()functions map a view of a file into a process's address space.

With oneimportant exception, file views derived from a single file mapping object arecoherent, or identical, at a given time. If multiple processes have handlesof the same file mapping object, they see a coherent view of the data when theymap a view of the file. The exception has to do with remote files. AlthoughCreateFileMapping()works with remote files, it does not keep them coherent. For example, if twocomputers both map a file as writable, and both change the same page, each computerwill only see its own writes to the page. When the data gets updated on thedisk, it is not merged. A mapped file and a file accessed by means of the inputand output (I/O) functions (ReadFile()and WriteFile())are not necessarily coherent. To fully close a file mapping object, an applicationmust unmap all mapped views of the file mapping object by calling UnmapViewOfFile(),and close the file mapping object handle by calling CloseHandle().The order in which these functions are called does not matter. The call toUnmapViewOfFile() is necessarybecause mapped views of a file mapping object maintain internal open handlesto the object, and a file mapping object will not close until all open handlesto it are closed. Terminal Services sessions can use shared memory blocks totransfer data between processes spawned by those sessions. If you do this, keepin mind that shared memory cannot be used in situations where both of the followingconditions exist:

  1. Allof the processes using the shared memory block were not spawned by one session.

  2. Allof the sessions share the same user logon credential.

 

To guardagainst an access violation, use structured exception handling to protect anycode that writes to or reads from a memory mapped view.

Windows Me/98/95: CreateFileMappingW()is supported by the Microsoft Layer for Unicode. To use this, you must add certainfiles to your application, as outlined in Microsoft Layer for Unicode on Windows95/98/Me Systems. To implement a mapping-object creation function that failsif the object already exists, an application can use the following code.

hMap = CreateFileMapping(...);

 

if (hMap != NULL && GetLastError() == ERROR_ALREADY_EXISTS)

{

    CloseHandle(hMap);

    hMap = NULL;

}

return hMap;

MapViewOfFile()

 

Item

Description

Function

MapViewOfFile().

Use

Maps a view of a file into the addressspace of the calling process. To specify a suggested base address,use the MapViewOfFileEx()function.

Prototype

LPVOIDMapViewOfFile( HANDLE hFileMappingObject, DWORD dwDesiredAccess,DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap);

Parameters

See below.

Return value

If the function succeeds, the returnvalue is the starting address of the mapped view. If the functionfails, the return value is NULL. To get extended error information,call GetLastError().

Include file

<windows.h>

Remark

See below.

 

Table 9.

 

Parameters

 

hFileMappingObject- [in] Handle to an open handle ofa file mapping object. The CreateFileMapping()and OpenFileMapping()functions return this handle.

dwDesiredAccess -[in] Type of access to the file viewand, therefore, the protection of the pages mapped by the file. This parametercan be one of the following values.

 

Value

Meaning

FILE_MAP_WRITE

Read/write access. The mapping objectmust have been created with PAGE_READWRITEprotection. A read/write view of the file is mapped.

FILE_MAP_READ

Read-only access. The mapping objectmust have been created with PAGE_READWRITEor PAGE_READONLYprotection. A read-only view of the file is mapped.

FILE_MAP_COPY

Copy-on-write access. The mapping objectmust have been created with PAGE_WRITECOPYprotection. The system commits physical storage from the pagingfile at the time MapViewOfFile()is called. The actual physical storage is not used until a threadin your process writes to an address in the view. At that point,the system copies the original page to a new page backed by thepaging file, maps the page into the process address space, and changesthe page protection to PAGE_READWRITE.The threads in your process can access only this local copy of thedata, not the original data. If this page is ever trimmed from yourprocess’ working set, it can then be written to the paging filestorage that was committed when MapViewOfFile()was called.

This process only allocates physicalmemory when a virtual address is actually written to. Changes arenever written back to the original file, and are freed when thethread in your process unmaps the view.

Paging file space for the entire viewis committed when copy-on-write access is specified, because itis possible that the thread in your process will write to everysingle page. Therefore, enough physical storage space must be obtainedat the time MapViewOfFile()was called.

 

Table 10.

 

dwFileOffsetHigh -[in] High-order DWORD of thefile offset where mapping is to begin.

dwFileOffsetLow -[in] Low-order DWORDof the file offset where mapping is to begin. The combination of the high andlow offsets must specify an offset within the file that matches the system'smemory allocation granularity, or the function fails. That is, the offset mustbe a multiple of the allocation granularity. Use the GetSystemInfo()function, which fills in the members of a SYSTEM_INFOstructure, to obtain the system's memory allocation granularity.

dwNumberOfBytesToMap- [in] Number of bytes of the fileto map. If this parameter is zero, the entire file is mapped.

 

Some Remarks

 

Mapping afile makes the specified portion of the file visible in the address space ofthe calling process. Multiple views of a file (or a file mapping object andits mapped file) are said to be "coherent" if they contain identical data ata specified time. This occurs if the file views are derived from the same filemapping object. A process can duplicate a file mapping object handle into anotherprocess by using the DuplicateHandle()function, or another process can open a file mapping object by name by usingthe OpenFileMapping()function. A mapped view of a file is not guaranteed to be coherent with a filebeing accessed by the ReadFile()or WriteFile()function:

To guardagainst STATUS_IN_PAGE_ERRORexceptions, use structured exception handling to protect any code that writesto or reads from a memory mapped view. If the file mapping object is backedby the paging file (hFileis INVALID_HANDLE_VALUE),the paging file must be large enough to hold the entire mapping. If it isnot, MapViewOfFile()fails. For Windows Me/98/95:  MapViewOfFile()may require the swapfile togrow. If the swapfile cannot grow, the function fails.

 

memset(), wmemset()

 

Item

Description

Function

memset(), wmemset().

Use

Sets buffers to a specified character.

Prototype

void *memset(void*dest, int c, size_t count);

 

wchar_t*wmemset(wchar_t*dest, wchar_t c, size_tcount);

Parameters

dest- Pointer to destination.

c- Character to set.

count- Number of characters.

Return value

The value of dest.

Include file

memset()- <memory.h>or <string.h>,wmemset()- <wchar.h>

Remark

-

 

Table 11.

 

UnmapViewOfFile()

 

Item

Description

Function

UnmapViewOfFile().

Use

Unmaps a mapped view of a file fromthe calling process's address space.

Prototype

BOOL UnmapViewOfFile(LPCVOID   lpBaseAddress);

Parameters

lpBaseAddress- [in] Pointer to thebase address of the mapped view of a file that is to be unmapped.This value must be identical to the value returned by a previouscall to the MapViewOfFile()or MapViewOfFileEx()function.

Return value

If the function succeeds, the returnvalue is nonzero, and all dirty pages within the specified rangeare written "lazily" to disk. If the function fails, the returnvalue is zero. To get extended error information, call GetLastError().

Include file

<windows.h>

Remark

Although an application may close thefile handle used to create a file mapping object, the system holdsthe corresponding file open until the last view of the file is unmapped:

Files for which the last view has notyet been unmapped are held open with no sharing restrictions. ForWindows Me/98/95:  Files for which the last view has not yetbeen unmapped are held open with the same sharing restrictions asthe original file handle.

 

Table 12.

 

 

-----------------------------------------------------EndDLL functions---------------------------------------------------

 

 

 

 

 

 

 

Further reading and digging:

 

  1. Microsoft Visual C++, online MSDN.

  2. Structure,enum, union and typedef story can be found atC enum, typedef, define etc..

  3. ForMultibytes, Unicode characters and Localization please refer toUnicode & Multibyte 1 (Story) andUnicode & Multibyte 2 (Implementation).

  4. Windowsdata type information is inWindows data type.

  5. Check the best selling C / C++ and Windows books at Amazon.com.

 

 

 

 

| Main |Site Index |Download |Disclaimer |Privacy |