![]() |
Languages »
C / C++ Language »
General
Intermediate
Easy way to manipulate BSTR using CString classBy Rejeesh.T.SThis article is about safe and easy way to use BSTR using the CString class. |
VC6Win2K, Visual Studio, MFC, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
When we do COM or ActiveX programming, we often have to cope with BSTR strings.
Even thought there are APIs for BSTR manipulation, it is a bit difficult to safely manage
the BSTR string. This article presents an easy way to manage the
BSTR string using the CString class.
We usually use conversion macros like OLE2A, A2BSTR etc.
But before using these macros, we should specify USES_CONVERSION macro at
the beginning of the function in order to avoid compiler errors. We should also include
the atlconv.h file to use these macros. It is also difficult to directly do
operations like appending, searching etc. in a BSTR string.
There is an easy way to manipulate BSTR string using the MFC
CString class.
CString constructor accepts the LPCWSTR. LPCWSTR is nothing but the
unsigned short*. i.e. the BSTR. Apart from this the operator = is overloaded
in CString class to support assignment operation. CString class also contains a
member function AllocSysString() which returns the BSTR string corresponding to
the CString object. Use the API SysFreeString to free the
BSTR string when
we no longer need the BSTR string.
void f(BSTR bStr) { CString csStr = bStr; //or csStr(bStr); ... //Now we can do whatever we want with this csStr }
void SomeFunction() { ... CString csStr = "Hello World!"; BSTR bStr = csStr.AllocSysString(); f(bStr) //maniplate the BSTR ::SysFreeString(bStr); //finished using the BSTR ... }
We can also use temporary objects of the CString class as follows.
Suppose we want to compare the right 3 characters of a BSTR with another
string, we can do as shown in the below function by using a temporary CString object.
void SomeFun() { ... if(!CString(bStr).Right(3).Compare("man")) { //Do something } ... }
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 25 Sep 2001 Editor: Nishant Sivakumar |
Copyright 2001 by Rejeesh.T.S Everything else Copyright © CodeProject, 1999-2009 Web10 | Advertise on the Code Project |