convert ATL::CComBSTR to BSTR*

本文关键字:BSTR to CComBSTR ATL convert | 更新日期: 2023-09-27 18:18:24

我是c++新手。我创建了我的c# DLL。我创建了Managed 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*

convert ATL::CComBSTR to BSTR*

你需要这样做…

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);
}