Click here to Skip to main content
Click here to Skip to main content

Calling COM DLLs from Console Applications

By , 24 Apr 2002
 

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

About the Author

Amol Kakhandki
Web Developer
India India
Member
Amol is currently working for a software company in India.His background is an engineering degree in Industrial Electronics.
He has been implementing projects in COM,DCOM,LDAP using VC++ ,MFC,ATL.
This has to be one of my favorite card - Reward Hotel Starwood Preferred Guest Credit Card. Thanks and enjoy!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralNice for beginner..memberyogeshratna27 Mar '10 - 4:53 
Thanks,
It is nice for beginner.
Generalwrong multiply resultmemberfatal00531 May '06 - 4:03 
Hi,
i follow all the steps till the launch of exe file but i dont get the right result ,i get always this result : -858993460
 
thanks in advance
 
abdelaaziz
 
aizzou
GeneralCreateInstance fail Errormemberamitsax7627 Feb '06 - 0:06 
Hi,
I am using a COM DLL inside my Win32 DLL. This Win32 DLL in trn is loaded into my Java Application (using JNI).
The problem is that although to the best of my knowledge I am accessing the COM object through a single thread, still i randomly gets "CreateInstance Fail" error in the COM DLL.
What are the potential causes for the same.
 
Hoping a quick reply ...
 
Amit


Generalif we call from aspmemberuno20037 Oct '03 - 22:29 
Usually the function return a value. And this function return by reference.
Can you tell me how can i call this function in asp?

GeneralA simpler waymemberSerge Weinstock24 Apr '02 - 21:40 
A simpler way is to use the #import directive, furthermore it makes you code more "C++" like.
This a snippet from my code:
#include "stdafx.h"
#include <iostream>
#import "XDIClientD.dll"
 
int main(int argc, char* argv[])
{
	::CoInitialize(NULL);
 
	try
		{
		XDI::IDataPtr	data;
 
		HRESULT hr = data.CreateInstance(__uuidof(XDI::Data));
		if (hr != S_OK)
			{
			_com_issue_error(hr);
			}
		data->DoSomething();
		}
	catch (_com_error &e)
		{
		std::cout<<"Ouch! "<<(e.Description().length() != 0 ? (LPCSTR) e.Description() : e.ErrorMessage())<<std::endl;
		}
 
	::CoUninitialize();
 
	return 0;
}
 

GeneralRe: A simpler waymemberAmol Kakhandki24 Apr '02 - 22:49 
Thanks

GeneralUse smart pointer in the clientmemberDudi24 Apr '02 - 21:12 
ATL creates a tlb file for the client use.
Using the "import" directive helps the client to work with the COM object.
It creates a wrapper class that calls CoCreateInstance for you and manage
automatically the reference count.
for example:
Suppose you have a COM object named Calc with a method called
Add(int x,int y);
Here is the client code:
 
#import "Calc.tlb" no_namespace
main()
{
CoInitialize(NULL);
try
{
ICalcPtr pCalc(__uuidof(Calc));
int i = pCalc->Add(5,3);
}
catch(_com_error &e)
{
HRESULT hr = e.Error();
}
CoUninitialize();
}
 
ICalcPtr is a typedef for a _com_ptr_t class that mamanges working with a COM object (it calles Addref and Release automatically).
 
Always use this pattern with using COM as a client.
 

GeneralRe: Use smart pointer in the clientmemberAmol Kakhandki24 Apr '02 - 22:48 
Thanks
QuestionWhy use ClassFactory?memberAnonymous23 Apr '02 - 22:35 
Using CoCreateInstance() to get the Interface directly is simple and useful than ur code, I always do this in my testing code to invoke my component. And using CComPtr<> in atlbase.h is make this code more easy.
AnswerRe: Why use ClassFactory?memberAmol Kakhandki23 Apr '02 - 23:32 
You are right.
Its just that i have been using this code snippet for a while now.
 
If I am not at my workplace writing code , I am probably at Code Project.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 25 Apr 2002
Article Copyright 2002 by Amol Kakhandki
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid