6

MS IDL has syntax for specifying a defaultvalue for parameters. I tried to specify a default value for a function that accepts a VARIANT_BOOL:

[id(42)] HRESULT Foo([in, defaultvalue(VARIANT_TRUE)] VARIANT_BOOL bar);

And got the following error message:

error MIDL2035 : constant expression expected

What is the correct syntax for specifying that the default value of bar should be VARIANT_TRUE?

Motti
  • 110,860
  • 49
  • 189
  • 262

2 Answers2

7

VARIANT_TRUE is #defined in WTypes.h. You can't directly use it in your .idl. The common approach is to simply use the value directly, like it is done in mshtml.idl for example:

  [id(42)] HRESULT Foo([in, defaultvalue(-1)] VARIANT_BOOL bar);

Or you can add a #define to your .idl if you prefer, put it somewhere near the top:

#define VARIANT_TRUE -1
#define VARIANT_FALSE 0
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Did you know that using `TRUE` also works for `VARIANT_BOOL`? I'm curious as to which is the _official_ way to do this. – Motti Sep 26 '11 at 07:37
  • 1
    TRUE has the wrong value. Given that mshtml.idl is a core Microsoft header file, I'd assume that -1 is the *official* way. – Hans Passant Sep 26 '11 at 09:39
  • `TRUE` has the wrong value in C++, in IDL it seems that it has the correct value (see my answer). Regarding MSHTML.idl, where did you find it, I have the .tlh and .tli generated from the DLL but not an original .idl – Motti Sep 26 '11 at 12:00
  • In the Windows SDK include directory. And no, midl doesn't magically change a 1 to a -1. The only reason it seems to work is that most code will check for value != VARIANT_FALSE to check for true. Or if (value) {}. Sooner or later you're going to run into code that checks for VARIANT_TRUE. Ouch then. – Hans Passant Sep 26 '11 at 12:13
  • Found the idl. As for the value, try it yourself, it gets passed to C++ as `-1` not `1`. – Motti Sep 26 '11 at 12:23
  • Depends on the client runtime as well. Interpreters use late binding. – Hans Passant Sep 26 '11 at 13:23
1

Although one should not mix up bool, BOOL and VARIANT_BOOL it appears that in idl BOOL is interpreted as a VARIANT_BOOL value.

[id(42)] HRESULT Foo([in, defaultvalue(TRUE)] VARIANT_BOOL bar);

When called from VBScript with no parameter specified this reaches the C++ code as -1.

I'm not sure which way is more idiomatic TRUE or as @Hans suggested -1.

Motti
  • 110,860
  • 49
  • 189
  • 262