Click here to Skip to main content
15,880,972 members
Articles / Desktop Programming / ATL
Article

Beginner's Tutorial: COM/ATL Simple Project

Rate me:
Please Sign up or sign in to vote.
4.60/5 (75 votes)
1 Dec 19996 min read 577.2K   3.3K   232   98
The purpose of this tutorial is to give you an idea on how to create a COM Server using ATL, and then being able to call the server from both a Visual C++ and Visual Basic program.

Introduction

The purpose of this tutorial is to give you an idea on how to create a COM Server using ATL, and then being able to call the server from both a Visual C++ program, and a Visual Basic program. I am not going to go into the depths of COM details or burden you down with IDL, this tutorial is designed to show a new VC++ programmer, how easy "Simple" COM objects are to create using ATL, and to whet their appetite for wanting to learn more.

Step 1: Running the ATL COM Wizard

The first thing you need to do is to fire up Visual C++ and create a new project. Choose the "ATL COM AppWizard". In the project name call it "Simple_ATL". Set the location where you want this project to be saved in, then hit the Ok button. You will see a screen that gives you several choices. The first choice is "Server Type". We are going to build a Server DLL, so make sure that the Server Type is set to "Dynamic Link Library". The other three checkboxes below do not concern us for this particular project, so we can ignore them. Press the finish button to have the Wizard generate to appropriate files for you. A "New Project Information" window will appear to tell you what files are going to be created. Press the Ok button to accept this.

Step 2: Creating a new ATL object

Make sure you can see the "Workspace View" inside the VC++ IDE. You can do this by clicking the "View" menu, then choosing "Workspace". There will be three tabs, click on the "ClassView" tab. You should see "Simple_ATL Classes". Right click on this and choose "New ATL Object" from the popup menu. You will see a window like the following:

The ATL Object Wizard

The default choice (Simple Object) is what we want. Click the next button and you will be in the "ATL Object Wizard Properties" window. In the "Short Name" textbox, enter "First_ATL". Notice how the Wizard automatically fills in the rest of the textboxes for you. Click on the "Attributes" tab at the top. Here you have several choices to make. For the first choice, Threading Model, we will stick with the default Apartment Model. For the "Interface", click on "Dual". Finally, as we are not going to be concerned with "Aggregation", click on the "No" radio button. We need not worry about any of the three checkboxes at the bottom. Click on the Ok button and let the Wizard create our new ATL Simple Object.

ATL Object Wizard Properties

Step 3: Adding a method

If you click on the "ClassView" tab now in your workspace, you will notice that the Wizard added a bunch of things. The first thing we want to do is add a method. We can do this easily by right clicking on "IFirst_ATL" and choosing "Add Method".

Adding a method

Once you have clicked on "Add Method" you will see the "Add Method to Interface" window. Under the Return Type you can see that by default the method will return "HRESULT". In most cases you should leave this as is. The next textbox allows us to type in the Method Name. Lets type in "AddNumbers". The last textbox asks us the Parameters we wish to use. As we want to add two numbers together, and get a result back, we will use three parameters. The last parameter will be a pointer. Now without going into a 300 page tutorial on IDL, we need to type in the following in the parameter textbox:

[in] long Num1, [in] long Num2, [out] long *ReturnVal

In a nutshell, we are declaring two parameters as long, the values are going in [in], and a final value to return [out] the answer. (It might looking kind of weird the first time you see it, but once you read a book or two on COM, this will make more sense) Click on the Ok button. Click on the "ClassView" tab and expand all the "+" symbols so the tree is fully open to view. Under the top interface ("IFirst_ATL") you will see our "AddNumbers" method, and the parameters we gave it. Double click on this, and it will place you into the code. Add the following code:

STDMETHODIMP CFirst_ATL::AddNumbers(long Num1, 
                long Num2, long *ReturnVal)
{
    // TODO: Add your implementation code here
    *ReturnVal = Num1 + Num2;

    return S_OK;
}

Step 4: Compiling the DLL

Believe it or not, but you have a working COM Server built with ATL! Of course we need to compile it. To do this, press the "F7" button and let VC++ do its work. The compiler will grind away for a few seconds. The compiler will register your new DLL in the registry so that other programs can make use of it. Lets try it out.

Step 5: Testing the COM Server with Visual Basic

To start with, we will use Visual Basic to test out the COM Server. (If you do not have a copy of VB, you can skip ahead to the section on testing the COM Server in VC++) Fire up VB and choose "Standard EXE" as your project. Place a Command button on the dialog. Now we need to add a reference to the COM Server. Click on the "Project" menu and choose "References". Scroll down until you see "Simple ATL 1.0 Type Library" and click on it.

Adding VB Reference

Click the Ok button. Now, double click on the command button you placed earlier and VB will drop you into the code window for the command button. Add the following code:

VB
Private Sub Command1_Click()
    Dim objTestATL As SIMPLE_ATLLib.First_ATL
    Set objTestATL = New First_ATL

    Dim lngReturnValue As Long

    objTestATL.AddNumbers 5, 7, lngReturnValue

    MsgBox "The value of 5 + 7 is: " & lngReturnValue

    Set objTestATL = Nothing
End Sub

If your a VB programmer this should be pretty straight forward. We declare and object, call the "AddNumbers" from the COM Server, then display the results. Press the "F5" key to run to the VB project, click on the command button, and you should see the expected results:

Testing it in VB

Not too hard. Lets try this again, except with VC++.

Step 6: Testing the COM Server with Visual C

Save and close the Simple_ATL project if it is still open and create a new project. Choose a "Win32 Console Application" and name it "Test_ATL". Click the Ok button and accept the default (An empty project) for the next window. Click on the finish button, then hit the Ok button again. You should now have an empty project. Press the "Control" and "N" keys to add a file to this project. From the window, choose "C++ Source File" and name it "Test_ATL.cpp". Press the Ok button to accept. You should have a blank file open. We need to add some code now to test out the COM Server. Start adding the following code to the new cpp file:

// You need to point this header file to the directory
// you placed the Simple_ATL project

#include "..\Simple_ATL\Simple_ATL.h"
#include <iostream.h>

// Copy the following from the Simple_ATL_i.c file
// from the Simple_ATL project directory
// NOTE: You can actually skip copying these if you want
// and just include the Simple_ATL_i.c file, I simply added
// it for clarity to show where these const variables are
// coming from and what they look like

const IID IID_IFirst_ATL =
    {0xC8F6E230,0x2672,0x11D3,
    {0xA8,0xA8,0x00,0x10,0x5A,0xA9,0x43,0xDF}};

const CLSID CLSID_First_ATL =
    {0x970599E0,0x2673,0x11D3,
    {0xA8,0xA8,0x00,0x10,0x5A,0xA9,0x43,0xDF}};

void main(void)
{
    // Declare and HRESULT and a pointer to 
    // the Simple_ATL interface
    HRESULT         hr;
    IFirst_ATL      *IFirstATL = NULL;

    // Now we will intilize COM
    hr = CoInitialize(0);

    // Use the SUCCEEDED macro and see if 
    // we can get a pointer
    // to the interface
    if(SUCCEEDED(hr))
    {
        hr = CoCreateInstance( CLSID_First_ATL, NULL, 
            CLSCTX_INPROC_SERVER,
            IID_IFirst_ATL, (void**) &IFirstATL);

        // If we succeeded then call the AddNumbers 
        // method, if it failed
        // then display an appropriate message to the user.
        if(SUCCEEDED(hr))
        {
            long ReturnValue;

            IFirstATL->AddNumbers(5, 7, &ReturnValue);
            cout << "The answer for 5 + 7 is: " 
                << ReturnValue << endl;
            IFirstATL->Release(); 
        }
        else
        {
            cout << "CoCreateInstance Failed." << endl;
        }
    }
    // Uninitialize COM
    CoUninitialize();
}

Step 7: Compile and run the program

Compile the program by pressing the "F5" key, then run it by pressing the "Control" and "F5" keys. You should see a DOS window open up and giving you the expected results.

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow to use CString or char data type in an Interface Method Pin
rahulN3-Sep-03 0:53
rahulN3-Sep-03 0:53 
GeneralEvents Pin
cberam20-Aug-03 2:07
cberam20-Aug-03 2:07 
GeneralOLEDB PROVIDER Pin
Dee12127-Jun-03 3:24
sussDee12127-Jun-03 3:24 
GeneralBeter way to test in VC Pin
Nigel Atkinson10-Jun-03 12:56
Nigel Atkinson10-Jun-03 12:56 
GeneralRe: Beter way to test in VC Pin
Jinto Thomas5-Oct-04 1:04
Jinto Thomas5-Oct-04 1:04 
GeneralRe: Beter way to test in VC Pin
Nigel Atkinson5-Oct-04 17:12
Nigel Atkinson5-Oct-04 17:12 
GeneralRe: Beter way to test in VC Pin
benjnp2-Oct-05 16:16
benjnp2-Oct-05 16:16 
GeneralRe: Beter way to test in VC Pin
Nigel Atkinson2-Oct-05 16:49
Nigel Atkinson2-Oct-05 16:49 
Did you add

#import "..\Simple_ATL\Debug\Simple_ATL.DLL" no_namespace

or equvilent at the top of your stdafx.h file?



Nigel Atkinson

"Land a'hoy!" * CRASH * "I should av said that sooner eh?" - Eckles, The Goon Show

-- modified at 22:49 Sunday 2nd October, 2005

GeneralNot finding New ATL Object.... Pin
Dhirendra28-May-03 19:38
Dhirendra28-May-03 19:38 
GeneralRe: Not finding New ATL Object.... Pin
Member 29512822-Jun-05 9:23
Member 29512822-Jun-05 9:23 
QuestionCan Atl replace normal dll? Pin
Anonymous27-Jan-03 15:55
Anonymous27-Jan-03 15:55 
AnswerRe: Can Atl replace normal dll? Pin
Emil Åström27-Feb-03 0:29
Emil Åström27-Feb-03 0:29 
QuestionWho can tell me how convert a MFC program to a COM/ATL program ? Pin
QiShouFeng12-Sep-02 17:58
QiShouFeng12-Sep-02 17:58 
General"Testing the COM Server with Visual C"is BAD!!! Pin
Anonymous25-Aug-02 4:46
Anonymous25-Aug-02 4:46 
GeneralRe: "Testing the COM Server with Visual C"is BAD!!! Pin
peterchen12-Sep-02 10:57
peterchen12-Sep-02 10:57 
Generalappending to file Pin
SimonL31-Jul-02 6:45
SimonL31-Jul-02 6:45 
GeneralRe: appending to file Pin
mahdavi11011-Jan-04 7:27
mahdavi11011-Jan-04 7:27 
GeneralBad client sample for C++ Pin
Dudi Avramov2-Jul-02 3:58
Dudi Avramov2-Jul-02 3:58 
Generalgood Pin
sai26-Jun-02 22:02
sai26-Jun-02 22:02 
GeneralErr ON receive Parameters Pin
24-Apr-02 6:11
suss24-Apr-02 6:11 
GeneralI Love it Pin
brick15-Apr-02 16:46
brick15-Apr-02 16:46 
GeneralRe: I Love it Pin
14-May-02 14:08
suss14-May-02 14:08 
GeneralCompilation Problem!!! Pin
15-Feb-02 0:13
suss15-Feb-02 0:13 
GeneralRe: Compilation Problem!!! Pin
22-Mar-02 10:19
suss22-Mar-02 10:19 
QuestionCalling COM (dll) problem ? Pin
5-Feb-02 5:17
suss5-Feb-02 5:17 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.