How to use CoCreateInstance() to get a com object?

2019-04-29 00:50发布

I had registered a COM component.And I want to call it.

CLSID clsid;
RIID iid;
HRESULT hr = CLSIDFromProgID(OLESTR("se.mysoft"),&clsid);
LPVOID *pRet;
HRESULT hr1 = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, iid, pRet);

I can get the clsid successful, but where can I get the iid ?

I used OLE VIEWER find interface:

 [
 odl,
 uuid(F3F54BC2-D6D1-4A85-B943-16287ECEA64C),
 helpstring("Isesoft Interface"),
 dual,
 oleautomation
 ]
 interface Isesoft : IDispatch {

Then I changed my code:

CLSID clsid;
RIID iid;
IDispatch* pDispatch;
HRESULT hr = CLSIDFromProgID(OLESTR("se.mysoft"),&clsid);
HRESULT hr1 = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,  IID_IDispatch,(void **)&pDispatch);

But hr1 returned failed.

标签: c++ com mingw
2条回答
可以哭但决不认输i
2楼-- · 2019-04-29 00:59

Your COM class implements some interfaces and each interface has its IID identifier. So you need to get it from your COM component implementation. It's your code and you are expected to provide the identifier which exactly specifies what interface you are requesting.

Some COM classes implement well known interface, esp. IDispatch, the identifier for which is IID_IDispatch, or __uuidof(IDispatch).

UPD. Since you found that the interface of interest is Isesoft, your code will be:

CLSID clsid;
RIID iid;
IDispatch* pDispatch;
HRESULT nResult1 = CLSIDFromProgID(OLESTR("se.mysoft"), &clsid);
HRESULT nResult2 = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
  IID_Isesoft, (void **) &pDispatch);

To get Isesoft and IID_Isesoft, __uuidof(Isesoft) available to C++ code, you will need to import the definitions, which is typically either of then two:

  • additional vendor SDK includes e.g. #include "isesoft\sdk.h"
  • or #import "libid:..." with type library identifier (namespace and other attributes apply)

When you have HRESULT codes indicating failures, make sure to post the values.

查看更多
Rolldiameter
3楼-- · 2019-04-29 01:23

You should know the interface you want on your object, let call it IMyInterface.

IMyInterface* pItf = NULL;
hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IMyInterface, (void**)&pItf);
查看更多
登录 后发表回答