COM/VB6 interop: passing integer in variant

  • Thread starter Thread starter Lars von Wedel
  • Start date Start date
L

Lars von Wedel

Hello,

I have problems to implement a C# component which is called by a VB6
application through COM. A method Item accepts a variant as a parameter
which can contain either a string or an integer (as an index) to access a
collection.

In certain cases, the integer I extract from the variant is a System.Int32
and everything works fine. In other cases, however, the content is shown as
a System.Int16 (e.g. in the debugger) and it is not possible to convert it
to an int for example (an exception is thrown).

Any ideas about this?

Lars
 
Hello Lars,

It seems to be pretty simple:

// assume "index" is the passed variant (that is, "object" in C#)

int indexValue;

if (index is System.String)
{
string keyVal = index as System.String;
// Handle string indexation.
}
else if (index is System.Int32)
{
indexValue = index as System.Int32;
}
else if (index is System.Int16)
{
indexValue = (int)TypeConverter.ConvertTo(index,
typeof(System.Int32));
}
else
{
throw new ArgumentException();
}
 
Hello Dmitriy,

Dmitriy Lapshin said:
It seems to be pretty simple:

// assume "index" is the passed variant (that is, "object" in C#)

[...]
else if (index is System.Int16)
{
indexValue = (int)TypeConverter.ConvertTo(index,
typeof(System.Int32));
}
[...]

I tried this, but it yields an exception containing the message
"TypeConverter cannot convert System.Int16 to System.Int32". Changing the
second argument of the ConvertTo-call yields the funny string
"TypeConverter cannot convert System.Int16 to System.Int16".

Any other ideas? Is there a way to access the flags of a variant to see
what's really inside? I don't have source code for the calling app.

Lars
 
Hello,

Mattias Sjögren said:
else if (index is System.Int16)
{
indexValue = (short)index;
}

should hopefully work.
It does, indeed (where casting to an int does not!). But what's the
difference compared to using the TypeConverter?

Lars
 
Back
Top