如何在 IDL 中声明 IN、OPTIONAL 参数以及 OUT、RETVAL 参数

How to declare IN, OPTIONAL parameter along with OUT, RETVAL parameter in IDL

我有一个现有接口 API,它有一个 OUT、RETVAL 参数,如下所示

HRESULT Test([out, retval] VARIANT_BOOL *pVal);

我被要求添加一个可选的 IN 参数,因此我尝试了以下方法, 因为按规则的 RETVAL 参数应该是我被迫的最后一个参数 将可选的 IN 参数作为第一个参数

HRESULT Test([in, optional, defaultvalue(VARIANT_FALSE)] VARIANT_BOOL optFlag, [out, retval] VARIANT_BOOL *pVal);

当我尝试像下面这样调用这个 API 时,只有来自 C++ 组件的强制性 OUT 参数编译器出错,说这个调用需要两个参数

VARIANT_BOOL outFlag;
pInterface->Test(&outFlag);

请让我知道我在这里缺少什么来实现这个组合。

Microsoft IDL 编译器生成的 C++ 绑定不支持可选的 and/or 默认值功能。

从 C# 或类似语言中尝试。

MSDN on optional IDL attribute:

The [optional] attribute is valid only if the parameter is of type VARIANT or VARIANTÂ *.

您正在尝试将其应用于 VARIANT_BOOL

关于具有此类属性的参数的顺序也有提示:

The MIDL compiler accepts the following parameter ordering (from left-to-right):

  • Required parameters (parameters that do not have the [defaultvalue] or [optional] attributes),
  • Optional parameters with or without the [defaultvalue] attribute,
  • Parameters with the [optional] attribute and without the [defaultvalue] attribute,
  • [lcid] parameter, if any,
  • [retval] parameter

IDL 编译器在编译此类方法时发出警告:

warning MIDL2401: [defaultvalue] is applied to a non-VARIANT and [optional]. Please remove [optional] : [ Parameter 'optFlag' of Procedure 'Test' ...

不过,属性被编译到类型库中,可供导入程序使用。例如,C# 将方法导入为:

bool Test(bool optFlag = false);

这应该符合您的期望。然而,这更像是一个免费的奖励,因为类型库导入者可以自行决定自由解释标志(尤其是超出记录的限制)。 C++ #import 不生成带有可选参数的方法。