When calling a function that expects a BSTR it'd be nice to be able to write something like:
iFoo->function( bs"HELLO" );
However the only workaround I'm aware of is to use a wrapper that calls SysAllocString
etc., e.g.:
iFoo->function( WideString(L"HELLO").c_bstr() );
which is kind of ugly. Is there actually such an option to create a BSTR
literal?
Motivation: easier-to-read code, and faster runtime performance by avoiding an allocation and deallocation.
Clarification: I am only talking about situations where the caller (i.e. us) has ownership of the BSTR, for example: calling a function that takes a BSTR [in]
parameter. Of course, it would be silly to supply a pointer to a BSTR literal to a function which will go on to try and free the string.
L"\xA\0" "HELLO" + 2
– ParalogismSysFreeString()
on that :) – Minimalbstr_t
orCComBSTR
. – Biddickprintf("hello");
becauseprintf
might free the string! – ParalogismVariantChangeType
for example, Called from a loadedVARIANT
with a "literal" invalid BSTR for "1000" changing toVT_LONG
would be UB from the rafters. BSTR[in,out]
marshalling by-definition will free the inputBSTR
and replace it with an output-BSTR multiple times. There is zero sense in literal BSTRs. I just reread your comment and I think you agree. I concur, something being sent a[in] BSTR
should not be freeing it (exceptSysFreeString
of course). – Biddick[in, out] BSTR
, onlyBSTR *
which has callee-ownership. – Paralogism[in,out] BSTR
in MIDL will createBSTR *
in the generated header and proxy/stub (it did last I checked anyway; been awhile). I completely agree its all about ownership. – BiddickBSTR
is supposed to play by the rules, how it is built is not up to you; its up to MS. They document them, which is nice, but they're also free to change that. Trying to literalize that is easily, if not more, tedious than just playing by the rules. Ex: your proposed "very ugly" solution is not conforming (it doesn't have two terminating nulls). Why would you want to do that? And you can toss BSTR-caching, which COM does for you, out entirely. – BiddickBSTR
in their functions. Good question! – Biddick