代码改变世界

Dynamic Create COM Attribute

2011-05-17 20:44  ubunoon  阅读(400)  评论(0编辑  收藏  举报

Some time, we want our COM object will dynamic maintain it’s attribute, just like built-in COM object attribute. If we could do that ,we could add more attributes for COM object without  compile the souce code. It soud great.This COM object is very similiar with JavaScript object or other interpret lanuage object, for example: python.

We know that when we use IDispatch interface to implement the COM object, we will get the automation of the object. Using IDispath interface, the COM object method and attribute could be get at running-time dynamicly. So if we have changed the default behaviour of the IDiaptch interface implement,  we could get the dynamic attribute.

From aboving, we should change the action of the GetIDsOfNames and Invoke of the IDispatch interface, which may like that

STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames,
									LCID lcid, DISPID* rgdispid)
	{
		// first find from system IDL
		HRESULT hr = CDispatchImpl::GetIDsOfNames( riid, rgszNames,
								cNames, lcid, rgdispid);

		if ( DISP_E_UNKNOWNNAME == hr )
		{
			hr = S_OK;
			for (UINT i=0; i
			{
				if ( DISPID_UNKNOWN == rgdispid[i] )
				{
					// get the maintain dispid
					rgdispid[i] = GetPropOrMethodDispid(rgszNames[i]);
				}
				else
				{
					hr = DISP_E_UNKNOWNNAME;
				}
			}
		}
		return hr;
	}

and change the Invoke function to :

STDMETHOD(Invoke)(DISPID dispidMember, REFIID riid,
		LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult,
		EXCEPINFO* pexcepinfo, UINT* puArgErr)
	{
		HRESULT hr = S_OK;
		if ( IsDyanmicDispid(dispidMember) )
		{
			hr = InvokeDynamicPropOrMethod(dispidMember, riid,
						lcid, wFlags, pdispparams, pvarResult,
						pexcepinfo, puArgErr);
		}
		else
		{
			hr = CDispatchImpl::Invoke( dispidMember, riid, lcid, wFlags,
							pdispparams, pvarResult, pexcepinfo, puArgErr);
			if ( SUCCEEDED(hr) && pvarResult && VT_EMPTY == pvarResult->vt )
			{

				pvarResult->vt = VT_I4;
				pvarResult->lVal = 0;
			}
			if ( FAILED(hr) && pvarResult && dispidMember >= 0 )
			{
				pvarResult->vt = VT_NULL;	// return null to show error;
				hr = -hr;
			}
		}
		return hr;
	}

We using GetPropOrMethodDispid and InvokeDynamicPropOrMethod function to resolve the dynamic attribute of COM object. Of course, we should use list or map to save the dispid, attribute name and attribute value in COM object, which will be used at used by Invoke interface function.

from here you could download it :

DynamicAttribute Code  // 在墙外,默认已经有了代理地址。

实际地址为:

http://www.qtrstudio.com/blog/wp-content/uploads/2010/10/DynamicAttribute.zip

我的个人网站,就这么被墙了,郁闷!