Create a simple com object.

 

 

 

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
//CoGetClassObject() simply does half the job that CoCreateInstance() does.It returns a class factory.CoCreateInstance() 
//then call IClassFactory::CreateInstance() and releases the IClassFactory.You would only use it if you have a need 
//to create many objects of a certain coclass and want to optimize that.It avoids the cost of creating and releasing 
//the factory over and over again.

#include "stdafx.h"
#include <tchar.h> 
#include <iostream> 
#include <atlcomcli.h>
#include <atlbase.h>
#include "F:\codes\ATLProject1\ATLProject1\ATLProject1_i.h"

using namespace std;

void test()
{
    HMODULE hLib= LoadLibrary(_T("F:\\codes\\ATLProject1\\Debug\\ATLProject1.dll"));

    typedef   HRESULT(__stdcall *PDllGetClassObject)(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID* ppv);

    PDllGetClassObject p = (PDllGetClassObject)GetProcAddress(hLib, ("DllGetClassObject"));

    IClassFactory *pFac=0;
    
    HRESULT hr = NULL;
    hr = p(CLSID_LiJingJing, IID_IClassFactory, (void**)&pFac);
    if (SUCCEEDED(hr))
    {
        CComPtr<IClassFactory> pFac2(pFac);

        ILiJingJing *puk=0;
        hr = pFac->CreateInstance(0, IID_ILiJingJing, (void**)&puk);
        CComPtr<ILiJingJing> puk2(puk);
        if (puk2)
            puk2->Test();
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    CoInitialize(NULL);

    test();

    HRESULT hr = NULL;
    

    {
        CComPtr<ILiJingJing>    puk2;
        hr = puk2.CoCreateInstance(CLSID_LiJingJing);
        if (SUCCEEDED(hr))
            puk2->Test();
    }

    ILiJingJing *puk;
    //hr = CoGetClassObject(CLSID_LiJingJing, CLSCTX_INPROC_SERVER, NULL, IID_ILiJingJing, (void**)&puk);
    hr = CoCreateInstance(CLSID_LiJingJing, NULL, CLSCTX_INPROC_SERVER, IID_ILiJingJing, (void**)&puk);

    if (SUCCEEDED(hr))
    {
        
        puk->Test();
        
        
        //do nothing 
        puk->Release();
    }
    else
    {
        cout << "Failed to create object" << endl;
    }

    CoUninitialize();
    return 0;
}

 

Powered by Jekyll and Theme by solid

本站总访问量