百度好多都没有找到window下使用xpcom开发的完整例子,自己写了一个
首先,创建简单计算器组件calculator,新建接口文件ICalculator.h,类定义头文件Calculator.h和实现文件Calculator.cpp,
需要以下配置设置:
1、工程属性页——连接器——输入 ——附加依赖项 ,添加链接库 embedstring.lib nspr4.lib plc4.lib plds4.lib xpcomglue.lib
2、工程属性页——C/C++——预处理器 ——预处理器定义,添加宏 XPCOM_GLUE
MOZILLA_STRICT_API
3、工具——选项——VC++目录——包含文件,设置sdk路径gecko-sdk,gecko-sdk\nspr\include,gecko-sdk\xpcom\include,gecko-sdk\embedstring\include,\gecko-sdk\string\include
4、工具——选项——VC++目录——库文件,设置sdk库路径,gecko-sdk\xpcom\bin,gecko-sdk\nspr\bin,gecko-sdk\embedstring\bin
接口文件如下ICalculator.h:
#ifndef _CALCULATOR_H
#define _CALCULATOR_H
#include <nsCOMPtr.h> //必须包含
#include <nsISupports.h> //必须包含
// {8D9FD7F4-58F3-4b79-8A2B-B799677862B5}
#define CALCULATOR_IID \
{ 0x8d9fd7f4, 0x58f3, 0x4b79, { 0x8a, 0x2b, 0xb7, 0x99, 0x67, 0x78, 0x62, 0xb5 } }
#define CALCULATOR_CLASSNAME "A Simple XPCOM Sample"
#define CALCULATOR_CONTRACTID "@mydomain.com/XPCOMSample/Calculate;1"
// {A6BF4E0E-5B4F-4bce-A658-C3215DE64421}
#define CALCULATOR_CID { 0xa6bf4e0e, 0x5b4f, 0x4bce, { 0xa6, 0x58, 0xc3, 0x21, 0x5d, 0xe6, 0x44, 0x21 } }
class ICalculator:public nsISupports
{
public:
NS_DEFINE_STATIC_IID_ACCESSOR(CALCULATOR_IID)
NS_IMETHOD_(long) Add(long val,long vb) = 0;
protected:
private:
};
#endif
类定义文件Calculator.h:
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include "ICalculator.h"
class Calculator:public ICalculator
{
public:
NS_DECL_ISUPPORTS
Calculator();
virtual ~Calculator();
NS_IMETHODIMP_(long) Add(long val,long vb);
protected:
private:
};
#endif
实现文件:
#include <nsIGenericFactory.h>
#include "Calculator.h"
#include <stdio.h>
NS_IMPL_ISUPPORTS1(Calculator, ICalculator)
NS_IMETHODIMP_(long) Calculator::Add( long val,long vb )
{
printf("add ");
return val + vb;
}
Calculator::Calculator()
{
NS_INIT_ISUPPORTS();
}
Calculator::~Calculator()
{
}
NS_GENERIC_FACTORY_CONSTRUCTOR(Calculator);
static const nsModuleComponentInfo components[1] =
{
{
CALCULATOR_CLASSNAME,
CALCULATOR_CID,
CALCULATOR_CONTRACTID,
CalculatorConstructor
}
};
NS_IMPL_NSGETMODULE(CalculatorModule, components)
接下来,新建测试程序comtest,使用我们的组件,这里需要做的几件事情:
1、把上面生成接口文件拷到comtest目录,并添加到项目头文件
2、在comtest下新建components子目录,并把上面生成的Calculator.dll拷贝到该目录下
#include <stdio.h>
#include "ICalculator.h"
#include <nsCOMPtr.h>
#include <nsIComponentManager.h>
#include <nsIServiceManager.h>
#include <nsIComponentRegistrar.h>
#include <nsXPCOM.h>
#include <nsXPCOMGlue.h>
#include <stdlib.h>
int main(void)
{
nsresult rv = NS_InitXPCOM2(nsnull,nsnull,nsnull); //初始化xpcom
if (NS_FAILED(rv))
{
return 0;
}
nsCOMPtr<nsIComponentManager> compManger;
nsCOMPtr<ICalculator> calculator;
rv = NS_GetComponentManager(getter_AddRefs(compManger));
if (NS_FAILED(rv))
return rv;
rv = compManger->CreateInstanceByContractID(CALCULATOR_CONTRACTID,
nsnull,
NS_GET_IID(ICalculator),
getter_AddRefs(calculator));
if (NS_FAILED(rv))
return rv;
printf("result : %d \n",calculator->Add(4,5));
system("pause");
NS_ShutdownXPCOM(nsnull); //结束xpcom
return 0;
}