COM/VB6 interop: passing integer in variant

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
 
D

Dmitriy Lapshin [C# / .NET MVP]

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();
}
 
L

Lars von Wedel

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
 
L

Lars von Wedel

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top