Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calling COM DLLs from Console Applications

0.00/5 (No votes)
24 Apr 2002 1  
This Article explains how to call a COM DLL from a Console Application

Introduction

This article shows how to call a VC++ DLL from a Console Application in C.

Getting Started

  • Create a new ATL project for a DLL , Click Finish.
  • Use ATL Object Wizard to add a simple object, Short Name as mydll , accept defaults.
  • Using Class View Add Method to the new interface , Method Name as multiply and parameters as '[in] int ifirst,[in] int isecond,[out] int* result'.

Your method should look like this:

STDMETHODIMP Cmydll::multiply(int ifirst, int isecond, int *result)
{
  // TODO: Add your implementation code here
  *result = ifirst * isecond;

  return S_OK;
}

Build and register the DLL. Now Create a Win32 Console Application named 'CallCDLL'.

Includes

#include <stdio.h>
#include <objbase.h>
#include "dll4C.h" //contains prototype of method
#include "dll4C_i.c" //contains the Class ID ( CLSID ) 
//and Interface ID ( IID )

Your Main() should like this
int main(void)
{
  IClassFactory* pclsf;
  IUnknown* pUnk;
  Imydll* pmydll;
  int x,y;
  int result;
  
  //Initialize the OLE libraries
  CoInitialize(NULL);

  //get the IClassFactory Interface pointer
  HRESULT hr = CoGetClassObject(CLSID_mydll,CLSCTX_INPROC,NULL,
    IID_IClassFactory,(void**)&pclsf);

  if(!SUCCEEDED(hr))
  {
    printf("CoGetClassObject failed with error %x\n",hr);
    return 1;
  }

  //Use IClassFactory's CreateInstance to create the COM object
  //and get the IUnknown interface pointer
  hr = pclsf->CreateInstance(NULL,IID_IUnknown,(void**)&pUnk);

  if(!SUCCEEDED(hr))
  {
    printf("ClassFactory CreateInstance failed with error %x\n",hr);
    return 1;
  }

  //Query the IUnknown to get to the Imydll interface
  hr = pUnk->QueryInterface(IID_Imydll,(void**)&pmydll);

  if(!SUCCEEDED(hr))
  {
    printf("QueryInterface failed with error %x\n",hr);
    return 1;
  }

  //Use Imydll interface for multiplications
  printf("Input two numbers to multiply:\n");
  scanf("%d\n%d",&x,&y);
  pmydll->multiply(x,y,&result);//call the method using 
                         //the interface pointer

  printf("The product of the two numbers %d and %d = %d\n",
    x,y,result);//print the result

  //Release the interface pointers
  pmydll->Release();
  pclsf->Release();

  return 0;
}


Conclusion

That's it. Write to me for any explanations/suggestions.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here