更多的时候,我们是需要写代码去使用别人提供的COM.那么如何去使用别人的COM来开发程序呢?

 前段时间用ADO写了几个程序,对COM的使用还是有点感觉。

在调用别人的COM组件的时候,首先应该详细阅读该COM组件的说明文档,大体知道是怎么一回事。

第二点就是在你的工程中引入com组件,一般是一个DLL.

比喻在使用ADO组件的时候,需要在源文件中加上:

#import "c:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")

在使用Windows Fax组件的时候,需要在源文件中加上:

// Import the fax service Fxscomex.dll file so that fax service COM objects can be used.
// The typical path to Fxscomex.dll is shown.
// If this path is not correct, search for Fxscomex.dll and replace with the right path.
#import "c:\windows\system32\fxscomex.dll"

 

下一步之后,就是定义一些变量。然后给这些变量赋值,在ADO中,一般定义如下变量:

_ConnectionPtr m_pConn;
_RecordsetPtr m_pRs;
_CommandPtr m_pCmd;
IADORecordBinding *m_pBindPtr;

在Windows Fax中定义 

FAXCOMEXLib::IFaxServerPtr sipFaxServer;
FAXCOMEXLib::IFaxActivityPtr sipFaxActivity;
FAXCOMEXLib::IFaxDocumentPtr sipFaxDocument;
//定义一个传真工作列表对象
//FAXCOMEXLib::IFaxOutgoingJobs sipOutGoing;
_variant_t varJobID;

 

当然最重要的一点是一定要在你的程序中初始化COM库,代码比较简单:

初始化:

// 
// Initialize the COM library on the current thread.
//
hr = CoInitialize(NULL);

退出:

CoUninitialize();

 

做完了上面的部分,就是给刚才的变量赋值(赋值这个词可能不是很专业)了。感觉这一步,不同的组件直接的差距还是挺大的,关键是看组件的使用文档。至于说为什么会有这么大的不同,还不是很清楚。

ADO中是这样的代码:

_ConnectionPtr pConn("ADODB.Connection");
_RecordsetPtr pRs("ADODB.Recordset");
_CommandPtr pCmd("ADODB.Command");

Windows Fax中是这样的

hr = sipFaxServer.CreateInstance("FaxComEx.FaxServer");

 

剩下的就是阅读组件的使用文档,利用适当的逻辑完成你要实现的功能。

利用COM的时候,常常需要处理异常。一段典型的异常处理代码如下:

try{
}catch(_com_error &e )
{
     e.ErrorMessage()  e.Error()    e.ErrorInfo() e.Description()
}
 

 

 



收藏
0个人 收藏

关注Joomla中国微信公众号,随时获得最新的Joomla新闻资讯!