Click here to Skip to main content
15,892,161 members
Articles / Programming Languages / C++

A Simple XPCOM Tutorial

Rate me:
Please Sign up or sign in to vote.
4.93/5 (30 votes)
30 Jun 2010CPOL5 min read 153.1K   4K   45  
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 (rv == NS_ERROR_FACTORY_NOT_REGISTERED)
	if ( NS_FAILED(rv) )
	{
		NS_ShutdownXPCOM(nsnull);
		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
	//NS_RELEASE(iSample); 

	// Or Shutdown Service manager 
	// The nsIServiceManager instance that was returned by NS_InitXPCOM2 or nsnull.
	NS_ShutdownXPCOM(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.

License

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


Written By
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.

Comments and Discussions