MikeK's software notebook

MikeK's software notebook

What you will find

This used to be the place where I wrote stuff I was thinking about while working on the Mozilla project.

Maybe in the near future I'll start to update it again as I'm involved in a couple of new open-source projects - updates pending...

What is NS_DECL_ISUPPORTS and NS_DECL_ISUPPORTS_INHERITED good for?

Mozilla coding hintsPosted by Mike Kristoffersen 22 Apr, 2009 23:14:28
Looking at the Mozilla code, you have probably come across the NS_DECL_ISUPPORTS and NS_DECL_ISUPPORTS_INHERITED macros. These are actuall not Mozilla specific but rather part of XPCOM.

The purpose of these macros are reference counting and interface detection.

So instead of implementing the:

NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr);
NS_IMETHOD_(nsrefcnt) AddRef(void);
NS_IMETHOD_(nsrefcnt) Release(void);

functions that are declared in nsISupports, you add the NS_DECL_ISUPPORTS macro to your class definition, like:

class nsMyBasicClass : public nsISupports
{
public:
// Basic refcount and interface detection macro
NS_DECL_ISUPPORTS
}

Now, if you inherit from an interface that inherits from nsISupports, then you need to specify this interface too:

class nsMyInterfaceImplementerClass : public nsIMyGreatInterface
{
public:
// Basic refcount and interface detection macro
NS_DECL_ISUPPORTS
NS_DECL_NSIMYGREATINTERFACE
};


If you inherit from multiple interfaces then you just list them all instead of NS_DECL_NSIMYGREATINTERFACE in the example above.

The above "macros" take care of the prototyping of the functions, you also need to use some "macros" to implement the body of the functions.

In the case where there is a direct inheritance from nsISupports the "macro" should be:

NS_IMPL_ISUPPORTS0(nsMyBasicClass)

(Just put it anywhere in your source file)

If you implement multiple interfaces you replace the 0 in the end of the name with the number of interfaces that you implement, and list the names of these interfaces after the name of the class that implements them:

NS_IMPL_ISUPPORTS1(nsMyInterfaceImplementerClass, nsIMyGreatInterface)

In the case where you inherit from multiple classes that already implement the nsISupports interface, you can get an ambugity as to which functions to call to do the reference counting - to solve this you must use the NS_DECL_ISUPPORTS_INHERITED "macro" instead of the plain NS_DECL_ISUPPORTS "macro"

NOTE:
Remember that all pointers to interfaces/classes should use a reference with the type:

nsCOMPtr<nsMyType>

rather than a nsMyType*, as you don't wan't to take care of the reference counting manually.

  • Comments(0)

Fill in only if you are not real





The following XHTML tags are allowed: <b>, <br/>, <em>, <i>, <strong>, <u>. CSS styles and Javascript are not permitted.