CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

jobs.internet.com

internet.commerce
Partners & Affiliates
Condos For Sale
KVM Switches
Promos and Premiums
PDA Phones & Cases
Cell Phones
Find Software
Laptop Batteries
Compare Prices
Televisions
GPS
Server Racks
Imprinted Promotions
Memory Upgrades
Compare Prices


RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> COM-based Technologies >> ATL & WTL Programming >> Tutorials

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

A Simple COM tutorial using ATL
Rating:

C. Lung (view profile)
June 25, 1999

Environment: VC6 SP3, VB6 SP3, NT4 SP4, Windows 2000 Beta 3



(continued)



Download these IBM resources today!
e-Kit: IBM Rational Systems Development Solution
With systems teams under so much pressure to develop products faster, reduce production costs, and react to changing business needs quickly, communication and collaboration seem to get lost. Now, theres a way to improve product quality and communication.

Webcast: Asset Reuse Strategies for Success--Innovate Don't Duplicate!
Searching for, identifying, updating, using and deploying software assets can be a difficult challenge.

eKit: Rational Build Forge Express
Access valuable resources to help you increase staff productivity, compress development cycles and deliver better software, fast.

Download: IBM Data Studio v1.1
Effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life.

eKit: Rational Asset Manager
Learn how to do more with your reusable assets, learn how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse.

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 gonna go into the depths of COM details or burden you down with IDL, this tuorial 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 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 "Custom", instead of "Dual". Finally, as we are not going to be concerned with "Aggregation", click on the "No" radio button. We don't need to 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.



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".



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 kinda 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 interfaace ("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.



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:


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
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:



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

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;

	// 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;

			hr = IFirstATL->AddNumbers(5, 7, &ReturnValue);
			cout << "The answer for 5 + 7 is: " << ReturnValue << endl;
			hr = 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.

Downloads

Source for the server - 14.3 Kb

Source for the VB test project- 1.19 Kb

Source for the VC test project - 2.83 Kb

History

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Data Sheet: IBM Information Server Blade
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.


RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
OK simple & straightforward so far ... - harry_nak (01/10/2008)
excellent - ganesh pandit (06/21/2007)
Question - Virender chauhan (08/06/2005)
very helpful - vijaykumar channakeshava (07/16/2004)
simple but very useful - reviver (05/25/2004)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES