Search code examples
c++dllcom

How to use COM dll in my C++ program


I wish to use a COM dll in my C++ library. The way I figured going about it, is to #import the dll's .tlb file, which I did :

#import "mycom.tlb" no_namespace

The problem is , I don't quite know where to place this declaration. should it be inside the H file or the CPP file? or maybe the stdafx.h file? I tried placing it in the .cpp file , just for testing.

in the H file I have this member declared :

ILogicSecuredPtr m_pbLogic;

(where ILogicSecured is the interface I want to work with in my COM dll)

Then I added this in the constructor to instantiate the interface :

CoInitialize(NULL);
m_pbLogic(__uuidof(LogicSecured)); 

(where LogicSecured is the name of the object that implements the interface)

In the destructor I added :

CoUninitialize();

This won't compile however, no matter where I try to place the #import declaration. it just doesn't recognize the ILogicSecured object. I get this error in the H file :

Error   2   error C2146: syntax error : missing ';' before identifier 'm_pbLogic'

I should also mention that when I F12 (in Visual Studio) on the ILogicSecuredPtr declaration, it takes me to the tlh file just fine. So I know it recognizes it.

What am I doing wrong here?

Thanks alot. Roey


Solution

  • The problem is that when the compiler parses the .h file it has not seen the #import yet. Since your project is small your best bet is to put #import into stdafx.h.

    When you press F12 Visual Studio uses Intellisence database information that is formed parsing all the sources in order that might be different from the compilation order. So it's quite typical to have Intellisence know where something is declared and the compiler to not compile it at the same time.