Understanding strings in COM

zhaozj2021-02-08  213

Understanding strings in COM

Davide marcato

System notes

To Replicate The Steps Described in this Article, You'll NEED Windows 95 or Windows NT 4.0 And Visual C 5.0 or Higher.

ANSI and Unicode, char and wchar_t were not enough: COM introduced several new string data types, and the differences and the process of conversion are not always obvious to the uninitiated This article clarifies the situation once and for all for the benefit of raw COM. , ATL and MFC Programmers.

Strings, ie vectors of alphanumeric characters, are and have always been a fundamental data type in every programming language and platform. Whereas the computer itself prefers to deal with numbers, human beings prefer messages of text to sequences of binary, hexadecimal or even decimal digits This Implies That WHENEVER A PIECT of SOFTWARE NEEDS To Interact with The User (OR Signal Some Notable Events) Some Kind of String Treatment is Likey to come into play.

Until a few years ago strings were just strings, that is, arrays of single-byte data types (char in C / C ) containing the ASCII number of the character at each element. The biggest problem was distinguishing zero-terminated strings (also known as ASCIIZ) from non-zero-terminated arrays. Then came Unicode, a new character set which extended the size of each character from 8 to 16 bits, thus allowing for 65536 theoretical different characters, enough to contain also Far Eastern symbols such as the kanji standard set. In C / C a brand new standard data type was defined to store Unicode strings, wchar_t, and consequently the APIs of Unicode-aware Win32 operating systems that took strings as parameters had to be duplicated to accept both ANSI and Unicode versions .Just as the Windows programmer community began to get acquainted with this duplication and got into the habit of not assuming anything about the length of a character a priori, COM jumped to the central stage with its burden of new types and aliases. If you are wondering what is the functional difference between an array of OLECHARs and a pointer to a BSTR, when and how it is necessary to convert a string to another type, and what degree of assistance ATL and MFC offer to the Developer, this article is for you.

Olechars

The main string data type in COM is named OLECHAR, which is the kind of variable expected by almost all COM library functions and well-educated interfaces' methods. An OLECHAR represents a single OLE-compatible character, therefore you can speak of a string only when you have an array of OLECHARs. It is obvious to everyone who has utilized C for some time that there is not an OLECHAR built-in data type in the language, as underlined (among other things) by the upper case of the name. The C and C standard specifications dictate the existence of only two character types:. char and wchar_t Hence, OLECHAR must be an alias to one of them, and in fact it is Its relation is established by the standard Win32 header file wtypes.h. , which we will meet again later in this article The following code snippet, adapted from the header file for clarity, represents the official definition of OLECHAR in C / C :.! # if defined (_WIN32) && defined (OLE2ANSI) typedef WCHAR OLECHAR ; #ELSE Typedef Char Olecha R; #ndif

The Same File Defines Also The LpoLestr and LPColestr Types:

! #If defined (_WIN32) && defined (OLE2ANSI) typedef OLECHAR __RPC_FAR * LPOLESTR; typedef const OLECHAR __RPC_FAR * LPCOLESTR; #else typedef LPSTR LPOLESTR; typedef LPCSTR LPCOLESTR; #endif

as aliases of OLECHAR * and const OLECHAR * in Win32, but aliases of LPSTR and LPCSTR in Windows 3.1x. The __RPC_FAR symbol can be ignored as it expands to nothing, so for all practical purposes BSTR and OLECHAR * can be deployed interchangeably.

As you can see, the BSTR type does not map to the same actual built-in type on every platform. If the code is compiled on 32-bit Windows, which can be detected from the _WIN32 preprocessor symbol definition, all COM characters are Unicode string (WCHAR is itself a typedef'ed data type that translates to the built-in wchar_t type). If not, then the build command is probably targeting Windows 3.1x, which does not support Unicode strings at all, so all the strings are regular old arrays of char. Note that on Sun Solaris, the main UNIX flavor to benefit from a porting of the (D) COM implementation to date, OLECHARs are 16-bit Unicode characters exactly as on Win32.The original Microsoft engineers who designed COM made a pretty courageous decision: They de facto imposed Unicode to everyone in the 32-bit world at a time when the original version of Windows NT was barely taking shape and the doubled amount of RAM required to hold the same strings could easily become problematic due To the HIGH cost of memory. But the decision proved advantageous, as it saved COM developers from having to implement two variants of each interface (and relative coclasses implementing it) just to deal with every possible type of client.

NOW We Have Seen How To Define A COM-Compliant String, But We Have Not Revealed Yet How One CAN Initialize Such A String With A String Litral. The Following Statement:

Const OLECHAR * PCOMSTR; PCOMSTR = "i love vcdj and com";

does work in Windows 3.1x because only ANSI strings exist there, but will fail to compile on Win32 and Solaris because we are trying to copy an ANSI string to a Unicode array of characters The following form.:

const OLECHAR * pComStr; pComStr = L "I love VCDJ and COM"; will give the exact opposite results: working on Win32, incorrect on Windows 3.1 What we really need is a way to define the type of a string irrespective of the platform. . Nothing Could Fit The Bill Better Thania Macro, AS in The Code Below:

Const OLECHAR * PCOMSTR; PCOMSTR = OLESTR ("i love vcdj and com");

. The OLESTR () macro is translated differently depending on the target of the build process, so we obtain the correct definition in all cases Wtypes.h reports it as follows, with some secondary adjustments made to clarify the original code:

#if defined (_win32) &&! defined (ole2ansi) #define Olestr (STR) L ## str #else #define Olestr (STR) STR #ENDIF

Note: In all other Win32 API implementations there is a discrepancy between Windows 95 / Windows 98 and Windows NT's string treatment, since the former employs one-byte ANSI characters and the latter internally works only with two-byte Unicode characters However, when it. Cubes To COM, Both Operating Systems Agree On The Use of Unicode Strings.

At this point you may be curious as to why the data type was called OLECHAR rather than the more obvious COMCHAR The answer to this question has its roots partly in history and partly in marketing:. Until a few years ago OLE2, the main family of technologies relying on the COM foundation, was deemed more important than COM itself, hence the acronym OLE spread everywhere. The later change of marketing orientation could not be reflected in the symbol names to avoid breaking a lot of existing and correctly functioning COM / OLE code . (See my Q & A column in VCDJ print and online for extensive info on this sometimes unclear transition of terms and intents.) OLECHARs are the standard way to create strings in COM code and by far the most comfortable as long as C and C are used In Both The Client Side and Tool Side. Other Languages ​​and Tools Bring Their Burden of Special Constraints That Open The Way To Another Kind of String, Which Constitute The Topic of The Next Paragraph.

Continue ...

Copyright © 1999 - Visual C Developeropers Journal

BSTRS

B-strings, more properly called Basic strings, are a special kind of string format. Instead of comprising a classic array of characters followed by a NUL character (code / 0) that marks the termination of the array, the structure of the data in memory is a superset of OLECHAR. In short, a BSTR is a null-terminated array of OLECHARs prefixed by its length. The string length is determined by the character count, not by the index of the first null character.

This presence of the length of the object before the actual array data renders these strings suitable for manipulation in high-level tools like Visual Basic (for which this string format was invented in the first place) and Java on a COM-aware virtual machine like Microsoft's JVM. Actually, there is no other way to exchange string-like data with components written in those languages ​​than to employ BSTRs. While in C and C the developer has to understand and use the data type in a rather uncomfortable manner, both Visual Basic and Java encapsulate them into their traditional string types, respectively String and java.lang.String. The final developer is therefore shielded from the subtleties of the organization of the raw bytes in memory. moreover, the tools take care of allocating and freeing the Memory Required To Contain Their Content WITHES.THIS IIS BEHIND The Scenes.this Is The Brilliant Side of the Medal of Course. You as The C / C Har dcore engineer get the tough part of the work, since you need to learn a completely new specific set of APIs that carry out the basic operations with Basic strings. The family of functions is amazingly named "system strings management API" and its members can easily Be distinguished by the "sys" prefix in their name.

The following code snippet, borrowed from Oleauto.h (this stuff used to be most useful when coupled with Automation, as Visual Basic's COM support was a lot less powerful then), shows the prototypes of each of the functions in the group:

/ * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------- * / / * bstr api * / / * ------------------- -------------------------------------------------- * / WINOLEAUTAPI_ (BSTR) SysAllocString (const OLECHAR *); WINOLEAUTAPI_ (INT) SysReAllocString (BSTR *, const OLECHAR *); WINOLEAUTAPI_ (BSTR) SysAllocStringLen (const OLECHAR *, UINT); WINOLEAUTAPI_ (INT) SysReAllocStringLen (BSTR *, const OLECHAR *, UINT); Winoleautapi_ (Void) sysfreestring (bstr); Winoleautapi_ (UINT) SYSSTRINGLEN (BSTR);

#ifdef _win32 winoleautapi_ (uint) SystringBytelen (BSTR BSTR); Winoleautapi_ (BSTR) sysallocstringBytelen (LPCSTR PSZ, UINT LEN); #ENDIF

Do not be unnerved by the probably unfamiliar WINOLEAUTAPI_ () word preceding all the functions; it is simply a macro defined in the same header file that expands to a long list of modifiers necessary to adjust the calling convention, exportation details, and return type YOU CAN Blissfully Ignore It for our purposes.

The Following Table Briefly Describes The Task of Each Routine:

Function name

Description

Sysallocstring ()

Allocates a new bstr and initializes it with an olechar *

SysReallocstring ()

Reallocates An EXISTING BSTR AND INITIALIZES IT with An Olechar *

Sysallocstringlen ()

Allocates a new bstr, Copies a specified Number of Characters from the passed olechar * INTO IT, AND THEN APPENDS A NULL Character

SysReallocstringlen ()

Reallocates an existing bstr, Copies a specified number of character of character, it, and then appends a null character

Sysfreeestring ()

Deallocates a BSTR

Systringlen ()

Returns the Number of Characters in A BSTR

SystringBytelen ()

Returns the length in bytes of a bstr (Win32 Only)

SysallocstringBytelen ()

Allocates a BSTR That Contains The Ansi String Passed As a parameter. Does not perform any ANSI-TO-Unicode Translation (Win32 ONLY)

The succinct description provided above, in conjunction with the official documentation, should be everything you will ever need to know to deal with BSTRs. Note that the expected usage pattern is the preventive allocation of an array of OLECHARs, which is later copied into the system String.

Basic strings must be allocated and freed manually. But who has the responsibility of doing so when function calls are involved? This is a general COM question and so the answer does not apply solely to strings. If the parameter is input-only (IDL attribute [in]) the caller is responsible for both the creation and the destruction of the variable. If the parameter is output-only (IDL attribute [out]) then the callee is responsible for the allocation of the string, but the caller is expected to free it after use. If the parameter is both input and output (IDL attribute [in, out]) then the caller allocates the string and after the method invocation frees the memory. The callee though is allowed to reallocate the string if necessary to Do So Before Returning It To The Caller.

Obviously The Details Interest C / C Developers Only To Treat Strings As Usual WITHOUT ANY Special Consideration.

BSTR Wrappers

Both ATL and MFC offer particular support for simplified BSTR management ATL does it by means of a specialized wrapper class, CComBSTR, whose declaration in atlbase.h looks like the following (stripped down as usual for clarity and space constraints).:

class CComBSTR {public: BSTR m_str; CComBSTR (); CComBSTR (int nSize, LPCOLESTR sz = NULL); CComBSTR (LPCOLESTR pSrc); CComBSTR (const CComBSTR & src); CComBSTR & operator = (const CComBSTR & src); CComBSTR & operator = (LPCOLESTR PSRC); ~ ccombstr (); unsigned int length () const; operator bstr () const; bstr * Operator & (); bstr copy () const; void attach (); void Empty (); #if _MSC_VER> 1020 bool operator ();! #else BOOL operator ();! #endif void Append (const CComBSTR & bstrSrc); void Append (LPCOLESTR lpsz); void AppendBSTR (BSTR p); void Append (LPCOLESTR lpsz, int NLEN); CComBSTR & operator = (const CComBSTR & bstrSrc); #ifndef OLE2ANSI CComBSTR (LPCSTR pSrc); CComBSTR (int nSize, LPCSTR sz = NULL); CComBSTR & operator = (LPCSTR pSrc); void Append (LPCSTR); #endif HRESULT WriteToStream (IStream * PStream); HRESULT READFROMSTREAM (ISTREAM * PSTREAM);}; The utilization of the class is very straightforward even for the Non-ATL Experts. Basical The Features Offered Area:

Encapsulation of the allocation and deallocation procedures forin the constructor and destructor;

Duplication of the contents; Possibility to append almost any kind of string to the wrapped bstr expedition of string the overloading

Support for Readable String Comparisons Through The Customized! Operator

Basic I / O Operations to Store The Contents of The String To, And Retrieve It from, A Structured Storage Stream.

On the other hand, MFC does not provide any direct wrapper class for system strings. All the support is an integral part of the extremely versatile Cstring class. As shown in the following code snippet borrowed from the class's prototype in afx.h, there are ONLY a COUPLE OF Methods Specify Generating COM STRINGS:

// Ole BSTR Support (Use for ole Automation) BStr AllocsysString () const; bstr setsystring (bstr * pbstr) Const;

Internally CString :: AllocSysString () allocates a new BSTR using the APIs we examined in an earlier paragraph and copies its contents to the newly created system string, which is eventually returned to the caller. There is no such function as CString :: FreeSysString ( ), so to deallocate the memory occupied by the returned BSTR, the global API :: SysFreeString () will have to be called. CString :: SetSysString () instead reallocates the BSTR pointed to by the parameter and copies its contents into it. Both Methods Throw CMemoryException Exception Objects in Case of Memory Allocation Problems.

Moreover, if you are using Visual C 5.0 or higher, you can exploit the Direct To COM proprietary extension which includes, among many other things, a _bstr_t class. The documentation reports that it is defined inside comdef.h, while in reality its declaration resides in comutil.h. The degree of encapsulation and functionality is similar to ATL's CComBSTR, but remember that using the COM compiler support binds you to Visual C even more than ATL would do. Probably the most relevant difference between the two implementations is that _bstr_t raises C exceptions and thus requires your code to be prepared to catch them, whereas CComBSTR does not This detail will likely influence your choice more than all the other possible considerations The following code listing summarizes the public interface of _bstr_t;.. the comments should make IT Easy to Understand What The Diverse Method Groups Are Up to: Class_BSTR_T {Public: // Constructors // _bstr_t () throw (); _bstr_t (const _bstr_t & s) throw (); _bstr_t (const char * s) throw (_com_error); _bstr_t (const wchar_t * s) throw (_com_error); _bstr_t (const _variant_t & var) throw (_com_error ); _BSTR_T (BSTR BSTR, BOOL FCOPY) throw (_COM_ERROR);

// deStructor // ~ _BSTR_T () throw ();

// Assignment operators // _bstr_t & operator = (const _bstr_t & s) throw (); _bstr_t & operator = (const char * s) throw (_com_error); _bstr_t & operator = (const wchar_t * s) throw (_com_error); _bstr_t & operator = ( const _variant_t & var) throw (_COM_ERROR); // Operators // _BSTR_T & OPERATOR = (const _bstr_t & s) throw (_BSTRROR); _BSTR_T OPERATOR (const _BSTR_T & S) Const throw (_COM_ERROR);

// Friend Operators // Friend_BSTR_T Operator (const char * s1, const _bstr_t & s2); friend _bstr_t Operator (const wchar_t * s1, const _bstr_t & s2);

// extractors // Operator const wchar_t * () const throw (); operator wchar_t * () const throw (); operator const char * () const throw (_EROM_ERROR); operator char * () const throw (_Com_error);

// comparison operators // Bool Operator! () Const throw (); Bool Operator == (const _BSTR_T & STR) const throw (); bool operator! = (Const _BSTR_T & STR) const throw (); Bool Operator <(Const _BSTR_T & S) Str); Bool Operator> (const_BSTR_T & STR) const throw (); BOOL Operator <= (const _BSTR_T & STR) const throw (); BOOL Operator> = (const _bstr_t & str) const throw ();

// low-level helper functions // bstr copy () const throw (_Com_ERROR); unsigned int length () const throw (); private: // [... private stuff itted ...]}

Continue ...

Copyright © 1999 - Visual C Developeropers Journal

Frameworks and convernesss

Your ideas of OLECHAR and BSTR and your understanding of the manner COM handles strings should be much clearer now, but we still have to cope with type conversions to and from these somewhat special data types and the more traditional TCHAR, WCHAR and char.

ATL and MFC both use the same group of macros to deal with string conversions These macros' names follow a precise convention:. The characters before the "2" indicate the original type of the variable to convert, and the characters after the "2" Indicate The Destination Type After the Conversion. The Following Table Lists The Valid Symbols in a Conversion Macro Name:

Short name

Data Type

A

LPSTR, CHAR *

Ole

LPolestr

T

LPTSTR, TCHAR *

W

LPWSTR, WCHAR_T *

BSTR

BSTR

C

Const - Associated to Another Type

The macros operate intelligently: if for some reason the source and destination types coincide, the code does not waste time in a useless process Internally most of the macros call the _alloca () run-time library function and allocate the storage for the new data. on the stack, as this simplifies the deallocation policy by delegating it to the rules of the variables scope. For this reason, a USES_CONVERSION macro must be put just before the conversion operation in each function or class method that contains the macros. The following sample Code, Taken From The Downloadable Sample Pack Available On The Web, Will Clarify The Process: // Conversions Through MFC / ATL'S Macros Void Sample2 () {USES_CONVERSION

// ANSI LPSTR ANSISTR = "this is a name message"; Printf ("Before The String Contains:% S / N", ANSISTR);

// Ansi -> const tchar const tchar * ptchar = a2ct (ANSISTR); _tprintf (_t ("Midway The String Contains:% S / N"), PTCHAR);

// constil -> Unicode LPWSTR WSTR = T2W (PTCHAR); WPRINTF (L "after the string contains:% s / n", wstr);}

As I stated earlier, the conversion macros are part of MFC and ATL, but surprisingly the header files are not directly shared by the two frameworks. ATL programmers should include Atlconv.h, while MFC developers are supposed to include Afxconv.h in their projects . After digging into the sources I found that in the latest versions of MFC, Afxconv.h does little more than include Atlconv.h itself, so in practice the string conversion code exposed by the two frameworks is the same.

The COM compiler support offers good BSTR conversion code, too. The actual conversion functions are the cast operators that convert a _bstr_t to either an ANSI or a Unicode string, either constant or not, plus the omnipresent class constructors. The following code snippet, taken From The Downloadable Sample Pack Available on The Web, Shows Some Common Usage Patterns of Bstr Conversions: // BSTR Conversions Void Sample3 () {Uses_Conversion;

LPWSTR WSTR = L "this is a name message"; WPrintf (L "Before The String Contains:% S / N", WSTR);

BSTR BSTR1 = W2BSTR (WSTR);

CString Mfcstr = BSTR1; Printf ("Midway The String Contains:% S / N", (LPCSTR) MFCSTR);

BSTR BSTR2 = mfcstr.allocsysystring (); _BSTR_T BSTR3 = BSTR2; Verify (BSTR3 == (_BSTR_T) BSTR1); Wchar * WSTR2 = BSTR3; WPRINTF (L "after the string contains:% s / n", WSTR2);

:: sysfreestring (bstr1) ;:: sysfreeestring (bstr2);

This is music to the ears of those who work with more or less advanced frameworks, but what about those who prefer (or are compelled) to stick to low-level C COM development? They can still use the standard library conversion function, which the framework macros themselves rely on ultimately, such as mbstowcs () and wcstombs (). Unfortunately such functions are not aware of BSTRs and OLECHARs, so heavy use of conditional compilation would be required to deal with the various combinations possible, and this is evil from a readability perspective. Power developers who program COM at the raw C level will probably find out naturally at a certain point in their learning curve and experience how to write a set of conversion macros by themselves. If you are lazy and prefer to use a precooked Set of macros, you can Freely Use Don Box's Yacl (The Acronym Stands for "Yet Another COM Library) Which IS Extreme Efficient and does Much More Than Just String Conversion In Pure C COM. The URL F or the download is http://www.develop.com/dbox/yacl.htm.conclusion

After some study and direct experimentation, the various string types in COM prove to be much less cryptic and problematic than at first they seemed. Fundamentally, it all boils down to recognizing and memorizing a handful of new data types which may behave differently on different platforms , and getting used to the framework of handy conversion functions provided by ATL, MFC, or the Direct to COM Visual C extension. Regardless of which of the mentioned tasks you are going to tackle, I hope this article will serve as a valuable aid in Saving precious time working with strings.

Article Index

转载请注明原文地址:https://www.9cbs.com/read-2677.html

New Post(0)