1.手动添加COM接口说明,例如
[ object, uuid(A7A5F961-2D82-4A85-8919-F3E23B0764D5), dual, helpstring("IMySample 接口"), pointer_default(unique) ] interface IMySample : IDispatch{ [, helpstring("方法Test")] HRESULT Test(); };
2.手动添加COM类,例如
[ uuid(2AC8F176-ACCB-46B0-B8B7-EBBDF06C415A), version(1.0), ] library TestComLib: { importlib("stdole2.tlb"); [ uuid(0DFAFCD4-2343-4AC1-9ED8-B1C773E05A31), helpstring("MySample Class") ] coclass MySample //添加COM类 { [default] interface IMySample; } };
3.添加MySample.rgs脚本,内容类似如下:
HKCR { NoRemove CLSID { ForceRemove {0DFAFCD4-2343-4AC1-9ED8-B1C773E05A31} = s 'MySample Class' //COM类GUID { ForceRemove Programmable InprocServer32 = s '%MODULE%' { val ThreadingModel = s 'Both' } TypeLib = s '{2AC8F176-ACCB-46B0-B8B7-EBBDF06C415A}' //类型库GUID Version = s '1.0' } } }
4.在resource.h文件中添加如下行:
#define IDR_MYSAMPLE 102
5.打开.rc文件,添加如下行:
IDR_MYSAMPLE REGISTRY "MySample.rgs"
6.在实现COM类的类体中加入如下红色标记的代码:
class ATL_NO_VTABLE CMySample : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CMySample, &CLSID_MySample>, public IDispatchImpl<IMySample, &IID_IMySample, &LIBID_TestComLib, /*wMajor =*/ 1, /*wMinor =*/ 0> { public: CMySample() { } DECLARE_REGISTRY_RESOURCEID(IDR_MYSAMPLE) BEGIN_COM_MAP(CMySample) COM_INTERFACE_ENTRY(IMySample) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } public: STDMETHOD(Test)() { return S_OK; } }; OBJECT_ENTRY_AUTO(__uuidof(MySample), CMySample)