Click to See Complete Forum and Search --> : passing strings from ATL to C#


ranadhir nag
April 15th, 2004, 10:27 PM
We have a strange problem in equating string and BSTR between a ATL server and c# client.
I have given a similar sample below.
What am i doing wrong?

c# client
=====

AirlineInfoObjClass _aobj=new AirlineInfoObjClass();
string _time=_aobj.GetAirlineTiming("IC5678");
Console.WriteLine("The timing is {0}", _time);


ATL DLL
=====
STDMETHODIMP CAirlineInfoObj::GetAirlineTiming(BSTR bstrAirline, BSTR *pbstrDetails)
{
// TODO: Add your implementation code here
USES_CONVERSION;
BSTR m_Airline=SysAllocString(L"IC5678");



if(m_Airline == bstrAirline)
{
*pbstrDetails = SysAllocString (L"16:45:00 - Will arrive at Terminal 3");

}
else
{
// Return the Airline name if not found
*pbstrDetails = bstrAirline;

}
return S_OK;

}

The above always returns me the airline name,whiel theoretically it should return the "16:45:00........" message.

Yves M
April 19th, 2004, 08:17 AM
In C++, a BSTR is just a pointer, so your comparison m_Airline == bstrAirline compares the pointer values, which will probably be different indeed. Instead, you should compare the strings, as in:

if (wcscmp(m_Airline, bstrAirline) == 0)

In addition to that, you are violating a COM rule in your ATL code. pbstrDetails is an [out] parameter, so you *always* have to give it its memory. The offending line is:

*pbstrDetails = bstrAirline;

This should rather be:

*pbstrDetails = SysAllocStringLen(bstrAirline, SysStringLen(bstrAirline));