0

i need to instantiate com object which is .dll and on local machine in visual c++,i know that it can be done by using CoCreateInstance("clsid") ,but i am confused about declaration.so can anyone explain all steps involved? for late binding as well as early binding

  1. is any import/inclusion required
  2. how to declare com object ?
  3. any other steps required before createinstance (e.g CoInitialize?)

or provide any specific reference involving step by step code

user1176743
  • 5
  • 1
  • 4
  • thanks LihO and Seva both of your answers are really helpful, both shows two different ways, #import is more efficient but i can't find typelib of one of object,i am confused which answer i should accept as both are correct. – user1176743 Feb 02 '12 at 07:10

2 Answers2

0

First you have to call CoInitialize and don't forget to callCoUnitialize if initialization was successful.

So your code will have the following structure:

HRESULT hr = CoInitialize(NULL); 
if (SUCCEEDED(hr))
{
    try
    {
        CoCreateInstance(...)
        // ...
    }
    catch (_com_error &e)
    {
        //...
    }
    CoUninitialize();
}

For more information visit MSDN. I recommend you to start with The COM Library and then you should read something about CoInitialize and CoCreateInstance functions before you use them.

This tutorial could help you too: Introduction to COM - What It Is and How to Use It.

LihO
  • 41,190
  • 11
  • 99
  • 167
  • I remember the pair CoInitialize/CoUninitialize should be used, say, in main. If CoInitialize fails, there is little point in further process. Your answer suggests to call before each CoCreateInstance. – CapelliC Feb 01 '12 at 14:55
  • Yes, it is initialization of COM Library, that allows you to create instance of COM and work with it. – LihO Feb 01 '12 at 15:35
0
  1. #import is very much recommended. if you import the typelib with #import, you'll be using the Native COM framework, which isolates some gritty details and makes life generally easier.

  2. In Native COM, something like this:

    LibName::IMyInterfacePtr pInterface;

In raw C++:

IMyInterface *pInterface;

But see above.

  1. Call CoInitialize() in the beginning of the program, CoUninitialize() in the end. if running inside a DLL, then it's much more complicated.
Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281