Click here to Skip to main content
13,293,369 members (48,812 online)
Click here to Skip to main content


45 bookmarked
Posted 28 Jun 2010

A Simple XPCOM Tutorial

Step by step XPCOM creation and implementation in C++.
// XULTesting.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include "nsCOMPtr.h"
#include "../sample_xpcom/ISample.h"
#include "../sample_xpcom/Sample.h"
#include "nsServiceManagerUtils.h"

int _tmain(int argc, _TCHAR* argv[])
	static const char szContractId[] =
		"Your component's contract ID goes here";
	nsresult rv;

	nsCOMPtr<nsIServiceManager> servMan;

	// You Can Get the service manager several ways

	// Get Service manager : WAY 1
	rv = NS_GetServiceManager(getter_AddRefs(servMan));
	if (NS_FAILED(rv))
		printf("ERROR: XPCOM error [%x].\n", rv);
		return -1;

	//-----------End of Getting Way 1 -----------------

	// Get Service manager : WAY 2
	// Initialize XPCOM and check for failure ...
	/*rv = NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull); 
	if ( NS_FAILED(rv) )
		printf("Calling NS_InitXPCOM returns [%x].\n", rv);
		return -1;
	//-----------End of Getting Way 2 --------------------

	// Get the Component object;
	nsCOMPtr<ISample> iSample;
	rv = servMan->GetServiceByContractID(SAMPLE_COMPONENT_CONTRACTID, NS_GET_IID(ISample), getter_AddRefs(iSample));	

	if ( NS_FAILED(rv) )
		return -1;
	int nFirstVal, nSecondVal, nResult;
	nFirstVal= 5; 
	nSecondVal = 10;
	iSample->Add(nFirstVal, nSecondVal, &nResult);
	_tprintf(_T("\nThe Result is : %d\n"), nResult);
	// Shutdown XPCOM 
	// Here also several ways you can follow

	// Explicitly Releasing ISample

	// Or Shutdown Service manager 
	// The nsIServiceManager instance that was returned by NS_InitXPCOM2 or nsnull.
	return 0;	

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Md. Mazharul Islam Khan
Software Developer (Senior) Eyeball Networks Inc, Dhaka
Bangladesh Bangladesh
I strongly believe, a person's strongest point is to know his/her weak point. I try to be simple.

I have completed BSc in Computer Science & Engineering from Shah Jalal University of Science & Technology, Sylhet, Bangladesh (SUST).

Watch out for my other CodeProject Articles.

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 1 Jul 2010
Article Copyright 2010 by Md. Mazharul Islam Khan
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid