Introduction
If you live in Eastern Europe, Japan or the Middle East, and you write computer programs, you are probably familiar with Unicode. if you are writing programs in Visual C ++/MFC, then you probably have experienced some of the problems with trying to write code that runs under Unicode and ASCII. this article shocould help clear up some of the confusion. the principles here will work for anyone using Visual C ++ and/or MFC.
What is Unicode?
Unicode is a popular solution that has evolved to solve the 256-character ASCII limit problem. the ASCII character set is limited to 256 characters, numbered 0-255. for most Latin-based versions, this is fine; one set of upper-case characters, one set of lower-case characters, and a smattering of special characters (like punctuation, currency, etc .).
However, faster Asian and Eastern ages contain faster more than 256 characters, sometimes thousands more. since ASCII is limited to 256, there has been no simple way to write programs for ages with more than 255 characters.
Unicode replaces the ASCII standard with a much larger range for mapping numeric codes to characters of specified classes. It does this by doubling the bytes of the character in the program.
ASCII versus Unicode
An ASCII character is stored in one byte of memory (one byte has a numeric range of 0-255 ). in order to create enough space to store larger character sets for other versions, it was determined that the byte size for one character be increased to two bytes. this provides a numeric range of 0-65535, or 65534 characters.
Unfortunately, doubling the byte size also causes compatibility problems. most programs that are written on the ASCII standard simply assume that a character is one byte. using methods and functions in Windows programs take advantage of this. when these programs are compiled for Unicode, they break.
Visual c ++ Solutions
What does all this mean to you as a software developer? If you are writing programs in Visual C ++, it means you must now decide whether your program is to run internationally, or if it is to remain local to ASCII compliant markets.
There is some good news here. visual c ++ provides some built-in support for Unicode. the Appwizard in VC ++ allows the developer to decide whether or not to support Unicode before generating the application framework. the Win32 SDK contains several data types that allow UNICODE compliance, and MFC provides macros that convert generic text to Unicode data types. the developer only needs to change a few coding habits to write Unicode-friendly applications.
The character string
C programmers declare a character array with the char Keyword:
Char STR [100];
Function prototypes are declared:
Void strcpy (char * Out, char * In );
To adapt these declarations to two-byte per character Unicode, use the following:
Wchar_t STR [2, 100];
Or
Void wcscpy (wchar_t * Out, wchar_t * In );
Microsoft also provides a way to write code that is Preprocessor Reliant. when you create a new project in Visual C ++, and you decide that it shoshould support another character set, Appwizard puts a pre-processor statement into one of the header files. this tells the compiler what character set you are intending to support. from there, you can use the generic data types that are supplied with VC ++, And the Preprocessor will replace them with the correct data type depending on what character set you are supporting. this makes the code much easier to re-compile for other character sets.
To activate the Unicode Standard in Visual C ++, select build | settings from the File menu (in Visual C ++ 5, select project | settings ). select the C/C ++ tab. append the _ Unicode value to the "Preprocessor definitions" field.
In your code, you wocould use tchar wherever the keyword char wocould normally be used, and lptstr wherever char * wocould be used. string constants defined in quotes ("Hello, world") wocould be re-written using the text macro:
Text ("Hello, world ")
Microsoft provides several data types, including generic types, that are compatible with both ASCII and Unicode. All of these can be found in the Microsoft on-line documentation under generic data types or data types.
The Code
Here are some examples using one of the code fragments from the developing professional applications for Windows 95 and NT using MFC book by Marshall brain and Lance lovette.
This is the "Hello, world" application using the ASCII character set:
//************************************** * ******************* // From the book "Visual C ++ 2: developing professional // applications for Windows 95 and NT with MFC "// by Marshall brain and Lance lovette // published by Prentice Hall // copyright 1995, by Prentice Hall. // This code implements a simple "Hello world! "Program in MFC //********************************** * ************************ // hello. CPP # include <afxwin. h> // declare the application classclass chelloapp: Public cwinapp {public: Virtual bool initinstance () ;}; // create an instance of the application classchelloapp helloapp; // declare the main window classclass chellowindow: Public cframewnd {cstatic * cs; public: chellowindow () ;}; // The initinstance function is called each // time the application first executes. bool chelloapp: initinstance () {m_pmainwnd = new chellowindow (); m_pmainwnd-> showwindow (m_ncmdshow); m_pmainwnd-> updatewindow (); Return true ;} // The constructor for the window classchellowindow: chellowindow () {// create the window itselfcreate (null,"Hello world! " , Ws_overlappedwindow, crect (0, 0, 200,200); // create a static labelcs = new cstatic (); CS-> Create ( "Hello World" , Ws_child | ws_visible | ss_center, crect (50, 80, 150,150), this );}
The string constants must be changed to their Unicode counterparts. in the following code fragment, the same string constants are passed into the text macro. text will tell the Preprocessor to check and see what character standard is being used:
// The constructor for the window classchellowindow: chellowindow () {// create the window itselfcreate (null,Text ("Hello world! "), Ws_overlappedwindow, crect (0, 0, 200,200); // create a static labelcs = new cstatic (); CS-> Create (Text ("Hello world! "), Ws_child | ws_visible | ss_center, crect (50, 80, 150,150), this );}
When the Preprocessor encounters a generic data type, it checks the afxwin. h header file for the _ Unicode definition. the Preprocessor will then insert the proper data type based on whether or not the Unicode standard is defined.
The following is an example of one of the Win32 API generic data types from the Win32 system services book by Marshall brain:
//************************************** * ****************** // From the book "Win32 system services: the heart of Windows NT "// by Marshall brain // published by Prentice Hall // copyright 1994, by Prentice Hall. /// this Code sets the volume label for drive C. //************************************** * ******************* // drvsvl. CPP # include <windows. h> # include <iostream. h> void main () {bool success; char volumename [max_path]; cout <"Enter new volume label for drive C:"; CIN> volumename; success = setvolumelabel ("C :\\", volumename); If (SUCCESS) cout <"Success \ n"; elsecout <"error code:" <getlasterror () <Endl ;}
The character array declared at the top of this fragment will be declared as a two byte character array using the tchar data type. The text Macro will again be used for the string constants:
Void main () {bool success;TcharVolumename [max_path]; cout <Text ("Enter new volume label for drive C :");Cin> volumename; success = setvolumelabel (Text ("C :\\"), Volumename); If (SUCCESS) cout <Text ("Success \ n "); Elsecout <Text ("error code :")<Getlasterror () <Endl ;}
Generic Data Types in Visual C ++
Visual c ++ provides several MFC-specific data types for making applications tolerant to international character sets. these are defined generically, to make the application fully portable to Unicode, ASCII, DBCS (double byte character sets) and MBCS (multi byte character sets ). it is beyond the scope of this article to explain all of the differences between the character sets; MFC provides a transparent way of implementing them all. how these generic data types are mapped depends on which character set variable is set for the project: none (the default, which is automatically ASCII), MBCS, DBCS or Unicode. since this article is primarily about Unicode, I have provided the Mappings for ASCII and Unicode Character Types in the table that follows:
Generic MFC Data Type |
Map to ASCII |
Map to Unicode |
Notes: |
_ Tchar |
Char |
Wchar_t |
_ Tchar is a macro that maps to the ASCIICharData Type if Unicode is not set, andWchar_tWhen it is. |
_ T or _ text |
Char constant strings |
Wchar_t constant strings |
These are functionally identical macros. They are ignored (removed by the Preprocessor) for ASCII; for Unicode, these macros convert the string into the Unicode equivalent. |
Lptstr |
Char *, lpstr (win32) |
Wchar_t * |
A portable-32 bit pointer to a character string. It maps to the character type that is set for the project, as explained above. |
lpctstr |
Const char *, lpcstr (win32) |
Const wchar_t * |
A portable 32-bit pointer to a constant character string. it maps to the character type that is set for the project, as fig. |
By using the above generic data types, the developer is able to ensure that one variable set when the project is created, and the use of these generic data types in place of the byte-specific ones they replace, isAllThat is needed to compile an application that is friendly to both ASCII and Unicode. However, it is important to note thatThe above generic types areMicrosoft extensions; They are not ANSI compatible.For detailed descriptions of the generic data types that Microsoft provides, read the Microsoft documentationGeneric Data TypesAndUsing generic-text MappingsIn the Microsoft Help files.
Some technical notes
To compile MFC programs for Unicode, you must have access to the Unicode versions of the MFC libraries. The library files are available through a custom installation of Visual C ++.
It is important to note that not defining the Unicode standard may not have a visible effect on your program. for example, the code above will build and execute without difficulty whether the _ Unicode variable is set in the build settings or not. the problems arise when the developer begins using Win32 API functions that have more than one implementation.
When the developer uses an API function that has a dual implementation (as any of the Win32 API functions that take a char or string as a parameter will ), the compiler callthe correct function based on whether the _ Unicode variable is set. without the _ Unicode being defined the standard, the compiler will call the ASCII declared version of the function; the Preprocessor will strip out the "ignored" macros.
Conclusion
As we have shown, compiling applications for the Unicode standard is not difficult. as a mental shift, Unicode is unique in that the changes it requires are simple and intuitive. the extensions provided by Microsoft serve to make the choice of character set even more transparent. these simple changes help simplify the process of writing new applications, and changing old ones, for international markets.
Special thanks to Yoshihiro Mori, a software developer in Japan, for pointing out to us the need for Unicode clarification for our books, which are now starting to be published in the native versions of other countries.