VS2010调用Com组件

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 object's 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.

相关下载

代码下载

转载于:https://www.cnblogs.com/Reyzal/p/5494178.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值