获取字符串后,在CompStr(BSTR,BSTR)上访问冲突?

时间:2014-09-11 22:05:51

标签: c++ com bstr

我在尝试与c ++函数中的BSTR字符串进行比较时遇到了无法理解的访问冲突。无论出于何种原因,代码在大多数情况下都能正常运行。但有时,看似随机,它会抛出异常。这就是我正在做的事情:

BSTR myString; // also tried this with a CComBSTR, same result, but less often it seemed
pSomeObject->GetString(&myString);
if (!CompStr(someOtherString, myString))
{
  //do stuff
}

SomeObject :: GetString是:

STDMETHODIMP SomeObject::GetString(BSTR* outStr)
{
  if (!outStr) return E_POINTER;

  *outStr = ::SysAllocString(m_memberString);

  return S_OK;
}

我在CompStr中遇到了访问冲突:

inline bool CompStr(BSTR str1, BSTR str2)
{
  UINT len1 = ::SysStringLen(str1);
  UINT len2 = ::SysStringLen(str2);  // this is where I'm getting the access violation

  return CompStr(str1, len1, str2, len2);
}

关于我做错了什么或为什么失败的任何想法?

1 个答案:

答案 0 :(得分:1)

您没有初始化myString,也没有检查GetString()是否有错误结果。

BSTR myString = NULL; // CComBSTR initializes for you
if (SUCCEEDED(pSomeObject->GetString(&myString)))
{
    if (!CompStr(someOtherString, myString))
    {
        //do stuff
    }
}

STDMETHODIMP SomeObject::GetString(BSTR* outStr)
{
    if (!outStr) return E_POINTER;

    *outStr = ::SysAllocString(m_memberString);
    if (!*outStr) return E_OUTOFMEMORY;

    return S_OK;
}

另外,请确保将someOtherString分配为BSTR,否则SysStringLen()将无法使用CompStr()。我建议改为WCHAR*改为使用lstrlenW()BSTR。您可以将WCHAR*传递给inline bool CompStr(WCHAR* str1, WCHAR* str2) { UINT len1 = ::lstrlenW(str1); UINT len2 = ::lstrlenW(str2); return CompStr(str1, len1, str2, len2); }

{{1}}