Re: interfacing between BSTR, LPCTSTR, CComBSTR, _bstr_t
Jason S <jmsachs@gmail.com> wrote:
I notice that CComBSTR can be used with the COM method but _bstr_t
cannot, e.g.:
CComBSTR b1;
_bstr_t b2;
pComObject->Something(&b1); // works
pComObject->Something(&b2); // won't work
Make it
pComObject->Something(b2.GetAddress());
Also CComBSTR has Attach() and Detach() members to allow you to
control ownership w/o having to duplicate memory. But _bstr_t does
not. :(
It does as of VC7.1. I don't have VC6 handy to check at the moment.
I also notice that _bstr_t has the facilities to convert to a char *
if necessary, but CComBSTR does not.
ATL way is to use explicit conversion macros:
CComBSTR b;
SomeAPI(COLE2CT(b));
I therefore end up doing stuff like this a lot:
CComBSTR btemp; // short term storage
_bstr_t b; // long term storage, usually a member of a class
pComObject->Something(&btemp);
b = btemp; // store it for long term use.
If you insist on doing it this way, a more efficient sequence would be
CComBSTR btemp; // short term storage
pComObject->Something(&btemp);
_bstr_t b(btemp.Detach(), false);
This avoids any unnecessary copies.
Is there any way to get a _bstr_t to use the [out] parameter of a COM
method without copying the string?
[p.s. I am using VC6, has this been improved in later editions of the
compilers?]
How about this little bit of self-help:
class bstr_out {
public:
bstr_out(_bstr_t& b) : ref(b), bstr(0) {}
~bstr_out() { ref = _bstr_t(bstr, false); }
operator BSTR*() { return &bstr; }
private:
_bstr_t& ref;
BSTR bstr;
};
Now you can do
_bstr_t b;
pComObject->Something(bstr_out(b));
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925