Sunday, February 13, 2011

Win API- Learn Item1

EnumProcesses Function

Retrieves the process identifier for each process object in the system.

Syntax


BOOL WINAPI EnumProcesses(
  __out  DWORD *pProcessIds,
  __in   DWORD cb,
  __out  DWORD *pBytesReturned
);

Parameters

pProcessIds [out]
A pointer to an array that receives the list of process identifiers.
cb [in]
The size of the pProcessIds array, in bytes.
pBytesReturned [out]
The number of bytes returned in the pProcessIds array.

Return Value

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

Requirements


Minimum supported clientWindows 2000 Professional
Minimum supported serverWindows 2000 Server
HeaderPsapi.h
LibraryKernel32.lib on Windows 7 and Windows Server 2008 R2, Psapi.lib if PSAPI_VERSION=1 on Windows 7 and Windows Server 2008 R2, Psapi.lib on Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000
DLLKernel32.dll on Windows 7 and Windows Server 2008 R2, Psapi.dll if PSAPI_VERSION=1 on Windows 7 and Windows Server 2008 R2, Psapi.dll on Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000




 

GetModuleBaseName Function

Retrieves the base name of the specified module.

Syntax

DWORD WINAPI GetModuleBaseName(
  __in      HANDLE hProcess,
  __in_opt  HMODULE hModule,
  __out     LPTSTR lpBaseName,
  __in      DWORD nSize
);

Parameters

hProcess [in]
A handle to the process that contains the module.
The handle must have the PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights. For more information, see Process Security and Access Rights.
hModule [in, optional]
A handle to the module. If this parameter is NULL, this function returns the name of the file used to create the calling process.
lpBaseName [out]
A pointer to the buffer that receives the base name of the module. If the base name is longer than maximum number of characters specified by the nSize parameter, the base name is truncated.
nSize [in]
The size of the lpBaseName buffer, in characters.

Return Value

If the function succeeds, the return value specifies the length of the string copied to the buffer, in characters. If the function fails, the return value is zero. To get extended error information, call GetLastError.

OpenProcess Function

Opens an existing local process object.

Syntax

HANDLE WINAPI OpenProcess(
  __in  DWORD dwDesiredAccess,
  __in  BOOL bInheritHandle,
  __in  DWORD dwProcessId
);

Parameters

dwDesiredAccess [in]
The access to the process object. This access right is checked against the security descriptor for the process. This parameter can be one or more of the process access rights. If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the contents of the security descriptor.
bInheritHandle [in]
If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle.
dwProcessId [in]
The identifier of the local process to be opened. If the specified process is the System Process (0x00000000), the function fails and the last error code is ERROR_INVALID_PARAMETER. If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last error code is ERROR_ACCESS_DENIED because their access restrictions prevent user-level code from opening them.

Return Value

If the function succeeds, the return value is an open handle to the specified process.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Sample:
HANDLE h = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);

Saturday, February 12, 2011

Intro Function pointer

2.1  Define a Function Pointer

Regarding their syntax, there are two different types of function pointers: On the one hand there are pointers to ordinary C functions or to static C++ member functions. On the other hand there are pointers to non-static C++ member functions. The basic difference is that all pointers to non-static member functions need a hidden argument: The this-pointer to an instance of the class. Always keep in mind: These two types of function pointers are incompatible with each other.
Since a function pointer is nothing else than a variable, it must be defined as usual. In the following example we define three function pointers named pt2Function, pt2Member and pt2ConstMember. They point to functions, which take one float and two char and return an int. In the C++ example it is assumed, that the functions, our pointers point to, are (non-static) member functions of TMyClass.


// 2.1 define a function pointer and initialize to NULL
int (*pt2Function)(float, char, char) = NULL;                        // C
int (TMyClass::*pt2Member)(float, char, char) = NULL;                // C++
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;     // C++
 
 
 

2.5  Calling a Function using a Function Pointer

In C you call a function using a function pointer by explicitly dereferencing it using the * operator. Alternatively you may also just use the function pointer's instead of the funtion's name. In C++ the two operators .* resp. ->* are used together with an instance of a class in order to call one of their (non-static) member functions. If the call takes place within another member function you may use the this-pointer.


// 2.5 calling a function using a function pointer
int result1 = pt2Function    (12, 'a', 'b');          // C short way
int result2 = (*pt2Function) (12, 'a', 'b');          // C

TMyClass instance1;
int result3 = (instance1.*pt2Member)(12, 'a', 'b');   // C++
int result4 = (*this.*pt2Member)(12, 'a', 'b');       // C++ if this-pointer can be used

TMyClass* instance2 = new TMyClass;
int result4 = (instance2->*pt2Member)(12, 'a', 'b');  // C++, instance2 is a pointer
delete instance2;



 
http://www.newty.de/fpt/intro.html 

DLL

1. Creating a Simple Dynamic-Link Library

The following example is the source code needed to create a simple DLL, Myputs.dll. It defines a simple string-printing function called myPuts. The Myputs DLL does not define an entry-point function, because it is linked with the C run-time library and has no initialization or cleanup functions of its own to perform.
To build the DLL, follow the directions in the documentation included with your development tools.
For an example that uses myPuts, see Using Load-Time Dynamic Linking or Using Run-Time Dynamic Linking.

// The myPuts function writes a null-terminated string to
// the standard output device.
 
// The export mechanism used here is the __declspec(export)
// method supported by Microsoft Visual Studio, but any
// other export method supported by your development
// environment may be substituted.
 
 
#include <windows.h>
 
#define EOF (-1)
 
#ifdef __cplusplus    // If used by C++ code, 
extern "C" {          // we need to export the C interface
#endif
 
__declspec(dllexport) int __cdecl myPuts(LPWSTR lpszMsg)
{
    DWORD cchWritten;
    HANDLE hConout;
    BOOL fRet;
 
    // Get a handle to the console output device.

    hConout = CreateFileW(L"CONOUT$",
                         GENERIC_WRITE,
                         FILE_SHARE_WRITE,
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);

    if (INVALID_HANDLE_VALUE == hConout)
        return EOF;
 
    // Write a null-terminated string to the console output device.
 
    while (*lpszMsg != L'\0')
    {
        fRet = WriteConsole(hConout, lpszMsg, 1, &cchWritten, NULL);
        if( (FALSE == fRet) || (1 != cchWritten) )
            return EOF;
        lpszMsg++;
    }
    return 1;
}
 
#ifdef __cplusplus
}
#endif  

2.Using Load-Time Dynamic Linking

After you have created a DLL, you can use the functions it defines in an application. The following is a simple console application that uses the myPuts function exported from Myputs.dll (see Creating a Simple Dynamic-Link Library).
Because this example calls the DLL function explicitly, the module for the application must be linked with the import library Myputs.lib. For more information about building DLLs, see the documentation included with your development tools.

#include <windows.h> 

extern "C" int __cdecl myPuts(LPWSTR);   // a function from a DLL

int main(VOID) 
{ 
    int Ret = 1;

    Ret = myPuts(L"Message sent to the DLL function\n"); 
    return Ret;
}


3. Using Run-Time Dynamic Linking

You can use the same DLL in both load-time and run-time dynamic linking. The following example uses the LoadLibrary function to get a handle to the Myputs DLL (see Creating a Simple Dynamic-Link Library). If LoadLibrary succeeds, the program uses the returned handle in the GetProcAddress function to get the address of the DLL's myPuts function. After calling the DLL function, the program calls the FreeLibrary function to unload the DLL.
Because the program uses run-time dynamic linking, it is not necessary to link the module with an import library for the DLL.
This example illustrates an important difference between run-time and load-time dynamic linking. If the DLL is not available, the application using load-time dynamic linking must simply terminate. The run-time dynamic linking example, however, can respond to the error.

// A simple program that uses LoadLibrary and 
// GetProcAddress to access myPuts from Myputs.dll. 
 
#include <windows.h> 
#include <stdio.h> 
 
typedef int (__cdecl *MYPROC)(LPWSTR); 
 
VOID main(VOID) 
{ 
    HINSTANCE hinstLib; 
    MYPROC ProcAdd; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 
 
    // Get a handle to the DLL module.
 
    hinstLib = LoadLibrary(TEXT("MyPuts.dll")); 
 
    // If the handle is valid, try to get the function address.
 
    if (hinstLib != NULL) 
    { 
        ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts"); 
 
        // If the function address is valid, call the function.
 
        if (NULL != ProcAdd) 
        {
            fRunTimeLinkSuccess = TRUE;
            (ProcAdd) (L"Message sent to the DLL function\n"); 
        }
        // Free the DLL module.
 
        fFreeResult = FreeLibrary(hinstLib); 
    } 

    // If unable to call the DLL function, use an alternative.
    if (! fRunTimeLinkSuccess) 
        printf("Message printed from executable\n"); 
}


Related Topics

Run-Time Dynamic Linking

 

C++ API - learn item1

1. GetModuleFileName Function

Retrieves the fully-qualified path for the file that contains the specified module. The module must have been loaded by the current process.
To locate the file for a module that was loaded by another process, use the GetModuleFileNameEx function.

Syntax

DWORD WINAPI GetModuleFileName(
  __in_opt  HMODULE hModule,
  __out     LPTSTR lpFilename,
  __in      DWORD nSize
); 
 
If this parameter is NULL, 
GetModuleFileName retrieves the path of the executable file of the current process.
 
 

2. strrchr, wcsrchr, _mbsrchr

Scan a string for the last occurrence of a character.
char *strrchr(
   const char *string,
   int c 
);
wchar_t *wcsrchr(
   const wchar_t *string,
   wchar_t c 
);
unsigned char *_mbsrchr(
   const unsigned char *string,
   unsigned int c 
);

Parameters

string
Null-terminated string to search.
c
Character to be located.

Return Value

Returns a pointer to the last occurrence of c in string, or NULL if c is not found.


sample:
    // Get the executable file's full path
    ::GetModuleFileNameA(NULL, sPath, MAX_PATH);
    //delete file name, just leave the folder
    char* p = ::strrchr(dir, '\\');
    *(p + 1) = 0;

3.strcat_s, wcscat_s, _mbscat_s


 Append a string. These are versions of strcat, wcscat, _mbscat with security enhancements as described in Security Enhancements in the CRT.

errno_t strcat_s(
   char *strDestination,
   size_t numberOfElements,
   const char *strSource 
);
errno_t wcscat_s(
   wchar_t *strDestination,
   size_t numberOfElements,
   const wchar_t *strSource 
);
errno_t _mbscat_s(
   unsigned char *strDestination,
   size_t numberOfElements,
   const unsigned char *strSource 
);
template <size_t size>
errno_t strcat_s(
   char (&strDestination)[size],
   const char *strSource 
); // C++ only
template <size_t size>
errno_t wcscat_s(
   wchar_t (&strDestination)[size],
   const wchar_t *strSource 
); // C++ only
template <size_t size>
errno_t _mbscat_s(
   unsigned char (&strDestination)[size],
   const unsigned char *strSource 
); // C++ only

Parameters

strDestination
Null-terminated destination string buffer.
numberOfElements
Size of the destination string buffer.
strSource
Null-terminated source string buffer.

4.FindFirstFile Function

Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used).
To specify additional attributes to use in a search, use the FindFirstFileEx function.
To perform this operation as a transacted operation, use the FindFirstFileTransacted function.

Syntax

HANDLE WINAPI FindFirstFile(
  __in   LPCTSTR lpFileName,
  __out  LPWIN32_FIND_DATA lpFindFileData
);

Parameters

lpFileName [in]
The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?).
This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash (\). If the string ends with a wildcard, period (.), or directory name, the user must have access permissions to the root and all subdirectories on the path. In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 widecharacters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.
lpFindFileData [out]
A pointer to the WIN32_FIND_DATA structure that receives information about a found file or directory.

Return Value

If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found.
If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.
If the function fails because no matching files can be found, the GetLastError function returns ERROR_FILE_NOT_FOUND.



5.FindNextFile Function

Continues a file search from a previous call to the FindFirstFile or FindFirstFileEx function.

Syntax

BOOL WINAPI FindNextFile(
  __in   HANDLE hFindFile,
  __out  LPWIN32_FIND_DATA lpFindFileData
);

Parameters

hFindFile [in]
The search handle returned by a previous call to the FindFirstFile or FindFirstFileEx function.
lpFindFileData [out]
A pointer to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. The structure can be used in subsequent calls to FindNextFile to indicate from which file to continue the search.

Return Value

If the function succeeds, the return value is nonzero and the lpFindFileData parameter contains information about the next file or directory found.
If the function fails, the return value is zero and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.
If the function fails because no more matching files can be found, the GetLastError function returns ERROR_NO_MORE_FILES.

6. GetProcAddress Function

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

Syntax

FARPROC WINAPI GetProcAddress(
  __in  HMODULE hModule,
  __in  LPCSTR lpProcName
);

Parameters

hModule [in]
A handle to the DLL module that contains the function or variable. The LoadLibrary, LoadLibraryEx, or GetModuleHandle function returns this handle. The GetProcAddress function does not retrieve addresses from modules that were loaded using the LOAD_LIBRARY_AS_DATAFILE flag. For more information, see LoadLibraryEx.
lpProcName [in]
The function or variable name, or the function's ordinal value. If this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero.

Return Value

If the function succeeds, the return value is the address of the exported function or variable.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The spelling and case of a function name pointed to by lpProcName must be identical to that in the EXPORTS statement of the source DLL's module-definition (.def) file. The exported names of functions may differ from the names you use when calling these functions in your code. This difference is hidden by macros used in the SDK header files. For more information, see Conventions for Function Prototypes.
The lpProcName parameter can identify the DLL function by specifying an ordinal value associated with the function in the EXPORTS statement. GetProcAddress verifies that the specified ordinal is in the range 1 through the highest ordinal value exported in the .def file. The function then uses the ordinal as an index to read the function's address from a function table.
If the .def file does not number the functions consecutively from 1 to N (where N is the number of exported functions), an error can occur where GetProcAddress returns an invalid, non-NULL address, even though there is no function with the specified ordinal.
If the function might not exist in the DLL module—for example, if the function is available only on Windows Vista but the application might be running on Windows XP—specify the function by name rather than by ordinal value and design your application to handle the case when the function is not available, as shown in the following code fragment.