How to marshal array of bools in C++ to an array of bool in C#

2

I have the following COM visible property in a C# class:

[ComVisible]
bool[] Values;

I have an instance of the class in C++ and used the following code to set this property (only pseudocode)

CComSafeArray<VARIANT_BOOL> values(3);
values[0] = VARIANT_FALSE;
values[1] = VARIANT_FALSE;

HRESULT hr = instance->put_Values(values.Detach());

The last line of the above code returns COR_E_SAFEARRAYTYPEMISMATCH (0x80131533). I tried with BYTE and VARIANT (with BOOL), but no success.

Can anyone please help?

c#
.net
com
com-interop
asked on Stack Overflow Feb 5, 2013 by Liton

1 Answer

2

Took me a while to figure it out but I got it: pass VT_BOOL as the second template parameter to CComSafeArray:

CComSafeArray<VARIANT_BOOL, VT_BOOL> values(3);

Without that template parameter, the SAFEARRAY will be created with the VARTYPE VT_I2 (a 2-byte integer, because VARIANT_BOOL is an alias for short), which is not what a C# property of type bool[] expects.

answered on Stack Overflow Feb 5, 2013 by user1610015

User contributions licensed under CC BY-SA 3.0