Since a BSTR
is only a typedef
for wchar_t*
our code base has several (many?) places where string literals are passed to a method expecting a BSTR
this can mess up with marshallers or anyone who tries to use any BSTR
specific method (e.g. SysStringLen
).
Is there any way to statically detect this type of misuse?
I tried compiling with VC10 /Wall
and with static code analysis Microsoft All Rules but the following offending piece of code doesn't get flagged by either of them.
void foo(BSTR str)
{
std::cout << SysStringLen(str) << std::endl;
}
int _tmain()
{
foo(L"Don't do that");
}
Update: After trying to vandalize wtypes.h
into detecting these kinds of transgressions I've given up.
I tried two paths, both of which I got to work with my sample program above but once I tried a real project they failed.
- create a class named
BSTR
but since aVARIANT
has aBSTR
as a union member the new class couldn't have any constructors or assignment operators this broke every place wereNULL
was treated as aBSTR
. I tried to replaceNULL
with a type that has conversion operators but after adding dozens of new operators (comparison, conversion etc.) I started to run into ambiguous calls and gave up. - I then tried the way suggested by @CashCow and @Hans (makeing
BSTR
atypedef
to another type of pointer). That didn't work either, after addingtoBSTR
andfromBSTR
methods and littering comutil.h (_bstr_t
) and other places with conversions I finally got to the point where the compiler choked at headers produced from IDLs (default values are translated to literal wide strings).
In short I've given up on trying to achieve this on my own, if anyone knows of a code analysis tool that can help I would be very happy to hear about it.
SysStringLen
looks for) that's why it's incorrect to treat awchar_t*
as aBSTR
. – CapapieBSTR
is passed towcscmp
. – Capapietypedef enum class BSTRchar : wchar_t {} *BSTR;
doesn't work either... scoped enums don't have implicit upcast. – Radom