Monday, May 26, 2008

Returning string array From COM - ATL

1)     In IDL file add method with argument SAFEARRAY(BSTR)* retval method.

2)     Add methods in .h and .cpp file .( with argument type SAFEARRAY** )

 

Example:

Suppose in Visual studio we added a ATL simple object with name ComTestObject then
  
wizard
 will create ComTestObject.h, ComTestObject.cpp file and a new interface IComTestObject in ild    file will generate.
        Adde following Code to return array of string :

 

·         Edit IDL file

interface IComTestObject : IDispatch{

                  [id(1), helpstring("method GetValutArray")]

HRESULT GetValutArray([out,retval] SAFEARRAY(BSTR)* pValutarr);

};

·         ComTestObject.h
#include "atlsafe.h"
class ATL_NO_VTABLE
C
ComTestObject :..
{
      //{wizard generated code}
      public:
            STDMETHOD(GetValutArray)(/*[in,out]*/ SAFEARRAY** pValutarr);
      private:
            CComSafeArray<BSTR> m_ValutArray;
}

·         ComTestObject.cpp

STDMETHODIMP CComTestObject::GetValutArray(SAFEARRAY** pLarr)
{
      HRESULT lResult = S_OK; // return code for OLE functions
      ULONG ulCount = 2;//The number of elements in the array
      LONG lLBound  = 0;//The lower bound value; that is,
                        //the index of the first element in the array.
     lResult = m_ValutArray.Create(ulCount,lLBound);
      if(  S_OK == lResult)
      {
            m_ValutArray.SetAt(0,_T("Sen"));
            m_ValutArray.SetAt(1,_T("API"));
            *pLarr = m_ValutArray;
      }
      return lResult;
}

Consuming COM in C#.

Add COM refetence and add following code.

        public string[] GetVaultArray()
        {
            Array vaultArray = null;
            try
            {
                CTsetClass testObj = new CTsetClass();
                vaultArray = testObj.GetValutArray();
            }
            catch (COMException)
            {
                //Handle Exception
            }
            try
            {
                string[] vaultStringarray = (string[])vaultArray;
                return vaultStringarray;
            }
            catch (InvalidCastException)
            {
                //Handle Exception
            }
            return null;
        }

SenApi.com

 

No comments: