【问题标题】:convert ATL::CComBSTR to BSTR*将 ATL::CComBSTR 转换为 BSTR*
【发布时间】:2015-10-20 09:33:14
【问题描述】:

我对 C++ 很陌生。我创建了我的 C# DLL。我创建了托管 C++ DLL 并在我的 C# 项目中引用它。我想从 C# dll 返回 char* 中的字符串值问题是,我无法将 CComBSTR 转换为 BSTR

UINT    CHandler::GetData( UINT idx, char* lName) 
{
    HRESULT hRes= m_p->GetData(idx, CComBSTR(lName));
}

Error:  Fehler by CComBSTR(lNmae):  977 IntelliSense: It is no possible conversion of ""ATL::CComBSTR"" in ""BSTR *"" available.

我的 C# 函数有第二个参数,类型为 BSTR*

【问题讨论】:

  • 你的成员变量调用了什么GetData函数?
  • 这是我的 C# 函数 GetData(int idx, BSTR * lName)
  • @Brita 我明白你的问题,请参阅下面的答案。
  • 它需要一个指向 BSTR 的指针。所以你只需要创建一个,使用 m_p->GetData(idx, &CComBSTR(lName))。注意 & 运算符。 GetData() 返回后 BSTR 再次被销毁。
  • 感谢你这么多用户1,你的答案帮助我

标签: c# c++ bstr


【解决方案1】:

你需要做这样的事情......

CHandler::GetData调用COM接口获取char* lName

查看分配的内存是如何释放的。

UINT CHandler::GetData(UINT idx, char* lName) 
{
    BSTR bstrName;
    HRESULT hRes= m_p->GetData(&bstrName);

    char *p= _com_util::ConvertBSTRToString(bstrName);
    strcpy(lName,p);   //lName needs to be large enough to hold the string pointed to by p  
    delete[] p; //ConvertBSTRToString allocates a new string you will need to free

    //free the memory for the string
    ::SysFreeString(bstrName);
}

COM接口方法定义

语言:C++,请翻译成C# 基本上,你需要在c#方法中分配BSTR。

看看COM方法是如何分配和返回内存的

HRESULT CComClass::GetData(long idx, BSTR* pbstr)
{
   try
   {
      //Let's say that m_str is CString
      *pbstr = m_str.AllocSysString();
      //...
   }
   catch (...)
   {
      return E_OUTOFMEMORY;
   }

   // The client is now responsible for freeing pbstr.
   return(S_OK);
}

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 2010-09-15
    • 2013-05-12
    • 1970-01-01
    • 2011-12-01
    • 2013-05-24
    • 2012-01-28
    • 2023-03-14
    • 2010-11-28
    相关资源
    最近更新 更多