对VB6接口方法的后期绑定调用

时间:2016-07-28 18:08:32

标签: c++ interface com vb6

在我的C ++程序中,我使用了一个在VB6 COM DLL中实现的COM类。我们打电话给这个班级CETicketRA。此类具有AppliedPromotion类型的属性IPositionPromotionIPositionPromotion是由相同的VB6 COM DLL定义的接口。它有各种我尝试从C ++访问的属性和方法。

给出以下代码:

IDispatch* pETicketRA = NULL;
DISPPARAMS dispParams = {0};
VARIANT result;
VariantInit(&result);
// Left out: some code to set pETicketRA ...

OLECHAR* strAppliedPromotion = L"AppliedPromotion";
DISPID dispIDAppliedPromotion = -1;
HRESULT hr = pETicketRA->GetIDsOfNames(IID_NULL, &strAppliedPromotion, 1, LOCALE_SYSTEM_DEFAULT, &dispIDAppliedPromotion);
hr = pETicketRA->Invoke(dispIDAppliedPromotion, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dispParams, &result, NULL, NULL);
IDispatch* pPromo = NULL;
hr = result.pdispVal->QueryInterface(IID_IDispatch, reinterpret_cast<LPVOID*>(&pPromo));
VariantClear(&result);

现在我尝试阅读Foobar的属性IPositionPromotion

OLECHAR* strFoobar = L"Foobar";
DISPID dispIDFoobar = -1;
hr = pPromo->GetIDsOfNames(IID_NULL, &strFoobar, 1, LOCALE_SYSTEM_DEFAULT, &dispIDFoobar);

不幸的是,最后一次通话失败了DISP_E_UNKNOWNNAME

有没有人成功从C ++(或C#)调用VB6接口成员?

1 个答案:

答案 0 :(得分:0)

VB6使用显式接口实现。实现接口的方法不会成为实现对象的公共接口的一部分,并且为了调用它们,您需要明确地询问接口。如果您愿意,可以稍后从该界面中询问IDispatch,但您需要先查询该界面,因为您从对象本身获取IDispatch并从界面获得IDispatch由此对象实现的将是IDispatch es。

所以当你有:

' IInterface.cls
Public Sub Method()
End Sub
' Class1.cls
Implements IInterface

Private Sub IInterface_Method()
  MsgBox "!"
End Sub

并且您要创建Class1的实例并致电Method(),以下工作:

' Complile-time error: method not found
Dim c As Class1
Set c = New Class1

c.Method
' Run-time error: Object does not support this property or method
Dim c As Object    ' IDispatch
Set c = New Class1 ' QueryInterface for IDispatch from Class1

c.Method

以下内容将起作用:

Dim c As IInterface
Set c = New Class1

c.Method  ' Early binding
Dim c As IInterface
Set c = New Class1

Dim c_as_idispatch As Object   ' IDispatch
Set c_as_idispatch = c         ' QueryInterface for IDispatch from IInterface

c.Method  ' Late binding

您的C ++代码与上面的第二个非工作示例相同。

要解决此问题,请先QueryInterface IPositionPromotion,然后再查询IDispatch