Without USES_CONVERSION macro

I have this code that uses the USE_CONVERSION macro in a C ++ project ...

I was wondering if this is well written (not written by me), and if there are any better ways to do this without the USES_CONVERSION and W2A macros.

STDMETHODIMP CInterpreter::GetStringVar(BSTR bstrNamespace, BSTR bstrVar, BSTR *pbstrValue) { USES_CONVERSION; try { if (!pbstrValue) return E_POINTER; char* pszNamespace= W2A(_bstr_t(bstrNamespace).operator wchar_t*()); char* pszVar= W2A(_bstr_t(bstrVar).operator wchar_t*()); // Is this not better done another way???? char pszErrStr[kPYTHONERRBUFSIZE]; char pszStrValue[kPYTHONSTRVALUESIZE]; BOOL bResult= Python_GetStringVar(pszNamespace, pszVar, pszErrStr, pszStrValue, kPYTHONSTRVALUESIZE); *pbstrValue= _bstr_t(pszStrValue).operator BSTR(); if (!bResult) throw x::internal_error(A2W(pszErrStr)); return S_OK; } } 
+4
source share
1 answer

There is a class-based ATL :: CA2W and friends (in atlconv.h, I reckon) that do not push a line onto the stack and do not use macros. You do not need USES_CONVERSION in a function:

throw x::internal_error(ATL::CA2W(pszErrStr));

Also, since your arguments are BSTR (wchar_t *), you do not need to convert them to _bstr_t.

NOTE. The converted string lifetime is the lifetime of the CW2A object, so you will need to put it in a string class, for example:

CStringA arg = CW2A(bstrArg);

NOTE 2: pbstrValue is the output value. The _bstr_t instance will destroy the memory allocated for the BSTR. Therefore, you need to either directly use SysAllocString or disconnect the BSTR:

pbstrValue = SysAllocString(CA2W(retval));

or

pbstrValue = CComBSTR(CA2W(retval)).Detach();

NOTE 3. Explicit use of conversion operators ( .operator BSTR() ) is not required - the compiler will call the correct one for you.

NOTE 4: Since this looks like a COM call, you really don't want to throw a C ++ exception. You probably want to set an IErrorInfo object (perhaps with a helper):

if (!bResult) { SetError(CA2W(errorStr)); return E_FAIL; }

+5
source

Source: https://habr.com/ru/post/1313482/


All Articles