码迷,mamicode.com
首页 > 其他好文 > 详细

VS2010调用Com组件

时间:2016-05-15 02:28:51      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

Com组件开发过程中用的不多,资料也不多,故记录开发Com组件中的部分问题。

这一篇文章里,讲解了如何使用VS2010创建Com组件。现在基于该文章创建的Com组件接口,创建VC++项目来调用该接口。

使用流程

新建win32控制台项目。

主文件代码如下:

#include "stdafx.h"
#include "../testCom/testCom_i.h"
#include "../testCom/testCom_i.c"

int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr;
    IMyClass *pCom = NULL;
    CoInitialize(NULL);
    hr = CoCreateInstance(CLSID_MyClass,NULL,1,IID_IMyClass,(LPVOID*)&pCom);
    if (SUCCEEDED(hr))
    {
        LONG res;
        pCom->Add(2,3,&res);
        printf("2+3=%d\n",res);
    }
    CoUninitialize();
    return 0;
}

代码说明:

#include "../testCom/testCom_i.h"

#include "../testCom/testCom_i.c"

是将com组件定义接口的文件包含到本工程中,这样操作后才可以在后面直接调用Com接口函数。

调用Com组件前必须调用CoInitialize(NULL);

调用完成后需要释放CoUninitialize();

CoCreateInstance用于创建一个Com实例,函数说明如下:

HRESULT CoCreateInstance(
  __in   REFCLSID rclsid,
  __in   LPUNKNOWN pUnkOuter,
  __in   DWORD dwClsContext,
  __in   REFIID riid,
  __out  LPVOID *ppv
);

rclsid [in] 
The CLSID associated with the data and code that will be used to create the object.

pUnkOuter [in] 
If NULL, indicates that the object is not being created as part of an aggregate. If non-NULL, pointer to the aggregate objects IUnknown interface (the controlling IUnknown). 

dwClsContext [in] 
Context in which the code that manages the newly created object will run. The values are taken from the enumeration CLSCTX. 

riid [in] 
A reference to the identifier of the interface to be used to communicate with the object.

ppv [out] 
Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, * ppv contains the requested interface pointer. Upon failure, * ppv contains NULL.

相关下载

代码下载

VS2010调用Com组件

标签:

原文地址:http://www.cnblogs.com/Reyzal/p/5494178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!