ANSI版本和UNICODE版本的函数实现
2008年11月4日星期二
通常我们在编程中需要提供软件的ANSI版本和UNICODE版本,以提供更大的兼容空间。最新的windows操作系统已经将内部实现都转换为UNICODE编码了。尽管有很多API还有ANSI版本,但是其内部实现却是先转换为UNICODE,然后再调用UNICODE版本的函数。因此,我们在实际编写两个版本的函数实现时,也应该采用这种方法。下面通过一个小的控制台程序作为演示,详细代码如下:
函数实现头文件:
#include "windows.h"
// UNICODE
BOOL StringReverseW(PWSTR pWideCharStr,DWORD cchLength)
{
// Get a point to the last character in the string.
PWSTR pEndOfStr = pWideCharStr + wcsnlen_s(pWideCharStr,cchLength) - 1;
wchar_t cCharT;
// Repeat until we reach the center character in the string.
while (pWideCharStr < pEndOfStr)
{
// Save a charater in a temporary variable.
cCharT = *pWideCharStr;
// Put the last character in the first character.
*pWideCharStr = *pEndOfStr;
// Put the temporary character in the last character.
*pEndOfStr = cCharT;
// Move in one character from the left.
pWideCharStr++;
// Move in one character from the right.
pEndOfStr--;
}
// the string is reversed;return success.
return TRUE;
}
// ANSI
BOOL StringReverseA(PSTR pMultiByteStr,DWORD cchLength)
{
PWSTR pWideCharStr;
int nLenOfWideCharStr;
BOOL fOK = FALSE;
// Calculate the number of characters needed to hold the wide-character version of the string.
nLenOfWideCharStr = MultiByteToWideChar(CP_ACP,0,pMultiByteStr,cchLength,NULL,0);
// Allocate memory from the process's default heep to accomodate the size of the wide-character string.
// Don't forget that MultiByteToWideChar returns the number of characters,not the number of bytes,so
// you must multiply by the size of a wide character.
pWideCharStr = (PWSTR)HeapAlloc(GetProcessHeap(),0,nLenOfWideCharStr * sizeof(wchar_t));
if (pWideCharStr == NULL) return fOK;
// Convert the multibyte string to a wide-character string.
MultiByteToWideChar(CP_ACP,0,pMultiByteStr,cchLength,pWideCharStr,nLenOfWideCharStr);
// Call the wide-character version of this function to do the actual work
fOK = StringReverseW(pWideCharStr,nLenOfWideCharStr);
if (fOK)
{
// Convert the wide-character string back to a multibyte string.
WideCharToMultiByte(CP_ACP,0,pWideCharStr,nLenOfWideCharStr,pMultiByteStr,cchLength,NULL,NULL);
}
// Free the memory containing the wide-character string.
HeapFree(GetProcessHeap(),0,pWideCharStr);
return fOK;
}
#ifdef UNICODE
#define StringReverse StringReverseW
#define Printf wprintf
#else
#define StringReverse StringReverseA
#define Printf printf
#endif // !UNICODE
主文件:
#include "stdafx.h"
#include "ReverseString.h"
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR text[7] = _T("ABCDEF");
StringReverse(text,7);
Printf(_T("%s"),text);
getchar();
return 0;
}