Search code examples
c++dllcomc++builderc++builder-xe2

Use COM in C++ Builder


I'm new to COM libraries and I'm stuck on using a COM DLL in my C++ Builder (XE2) application. DLL is registered. Which are the steps that allows me to create objects belonging to such DLL and invoke their methods? I mean statically.

I couldn't find a tutorial, while I saw different ways:

  1. Component > Import component > it produces a new wrapper unit... and then what?
  2. import the DLL with an absolut path (why? it is registered in the system)

    #import "C:\Path\to\the\LIB1.dll" rename_namespace ("LIB1")
    

    ... and then what?

  3. use CoCreateInstance... how exactly? without import/include?

In Visual C# I deal with it simply adding a reference and a using!

I'm very confused! Any help is appreciated.


Solution

  • I found a way (but tell me if there are better ones):

    • Component > Import component... > Import a Type Library > select the library
    • Unit Dir Name = and uncheck "Generate Component Wrappers"
    • "Add unit to MyProject.cbproj project" > Finish
    • in the client class > File > Use Unit... > select the unit that was created
    • in the client class write this code for using the COM DLL:

      CoInitialize(NULL); //Init COM library DLLs  
      
      ICompany *company;        
      
      HRESULT hr = CoCreateInstance ( CLSID_Company,  
                                      NULL,  
                                      CLSCTX_INPROC_SERVER,  
                                      IID_ICompany,  
                                      (void**) &company );  
      if (SUCCEEDED (hr)) {  
           //TODO here you can use your company object!
           //and finally release such resource
           company->Release();  
      }  
      
      CoUninitialize();
      

    Where Company was the original class, exposed by the DLL, which I wanted to intantiate.

    Introduction to COM - What It Is and How to Use It. helped me a lot.

    Note that this requires the creation of *_TLB.* and *_OCX.* units. Is there a way that avoids it?