简体   繁体   中英

convert ATL::CComBSTR to BSTR*

I am very new with C++. I created my C# DLL. I created Managed C++ DLL and reference it in my C# project. I want to return from C# dll a string value in a char* Problem is, I can't convert CComBSTR to 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.

My C# function has second Parameter with type BSTR*

You need to do something like this...

CHandler::GetData calling COM interface to fetch char* lName

See how allocated memory is freed.

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 interface method definition

Language: C++, please translate it to C# Basically, you need to allocate BSTR inside c# method.

See how memory is allocated and returned by COM method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM