简体   繁体   中英

CString to _bstr_t conversion C++

I've inherited a MFC project from another developer. Under multiple MFC methods, calls are made to a COM server, passing strings as arguments. Here is a representative example of the conversion pattern in the current code base:

COM server:

void COMServer::foo(_bstr_t strParam)

MFC method:

void Foo::foo(CString &csParam)
{
     CComBSTR bstrParam(strDocName);
     ptrToComServer->foo((BSTR)bstrParam);
}

After reading about string conversion rules in this article , I'm wondering if the current pattern of conversion is

  • safe from a memory management standpoint
  • efficient in terms of the number of string copies made

With respect to the above two concerns, I'd also like to know if the following conversion would be better

void Foo::foo(CString &csParam)
{
    _bstr_t bstrParam(csParam);
    ptrToComServer->foo(bstrParam);
}

The legacy MFC method should be improved, by removing the (BSTR) cast.

void Foo::foo(CString &csParam)
{
     CComBSTR bstrParam(strDocName);
     ptrToComServer->foo(bstrParam);
}

I see no memory corruption in your existing code, or in your new proposal. As for efficiency, the two methods seem pretty identical to me.

If you are really concerned by performances (are you really sure that maters? Do you make several thousands per second COMServer::foo calls ) you should begin by (concerning your "strings"):

  1. Make your project UNICODE, if not already done, as it may buy you much less conversions before your COM calls.
  2. Try to use CComBSTR or _bstr_t as soon as possible, eventually avoiding the CString to BSTR copies/conversions.

Please use the following conversion,

CString aTestUser(_T("TestUser"));
_bstr_t aConvertedUser(aTestUser);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM