Brita
Brita

Reputation: 43

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*

Upvotes: 2

Views: 2286

Answers (1)

user1
user1

Reputation: 4131

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

Upvotes: 0

Related Questions