Monday, June 15, 2009

Using .NET component in C++ code

Referring a C++ COM component is easy in .NET; all we have to do is to
  • register (regsvr32 <dll_name_with_full_path>)
  • Add a reference to the COM dll in the Visual Studio Solution
  • An Interop file will be created in the bin directory of .NET project and we are done 
But the reverse is not as simple as above.
So this time I have come up with Steps we need to follow in order to refer a COM visible .NET dll in C++ code. 
  • Register the COM Visible .NET assambly with regasm like this:
regasm <dll_name_with_full_path> /tlb
e.g. regasm "C:\SampleProject\bin\Release\Atreya.Anugrah.ComVisibleComponent.dll" /tlb
  • Refer .NET component in .h file like this:
#import "<generated_tlb_name_with_full_path>" named_guids raw_interfaces_only
e.g. #import "C:\SampleProject\bin\Release\Atreya.Anugrah.ComVisibleComponent.tlb" named_guids raw_interfaces_only 
  • Create a class in .h file, and declare member variable like this:
ComVisibleComponent::<Name_of_Interface>* memberVariablePointer;
e.g. Atreya_Anugrah_ComVisibleComponent::IMyInterface* m_pIMyInterface; 
  • Now, Initialize the declared member variable pointer in .cpp file like this: 
hr = CoCreateInstance( __uuidof(Atreya_Anugrah_ComVisibleComponent::<Name_of_CoClass_Implementing_Interface>),          // COM class id
                                        NULL,                                                                                                                                                  // Outer unknown
                                        CLSCTX_ALL,                                                                                                                                       // Server INFO
                                        Atreya_Anugrah_ComVisibleComponent::IID_<Name_of_Interface>,                                                // interface id
                                        (void**) &m_pIMyInterface   );                                                                                                                 // Returned Interface 
if (FAILED(hr))
       _com_error e(hr);
   strErrorMsg.Format("Error: Unable to create COM Visible .NET component. hr = %d. Message = %s",hr, e.ErrorMessage());
   return hr;
          //you are good to use your initialized pointer here :)   
P.S. This post does not explain that how can we make our .NET component as COM visible. Please refer other post/article for that as it is quite simple activity.
Namaste (Thanks and Regards)
| Anugrah Atreya