Simple way to return a COM enumeration interface from .NET?

J

Jayme Pechan

Is there a simple way to return a COM enumeration interface from .NET? I am
porting a C++ COM Object that has an enumeration interface containing the
DISPID_NEWENUM and DISPID_VALUE properties and the count property and need
to create the equivilant in C#. I'm hoping I can just return an array list
or something but something tells me it isn't that easy. Any thoughts on the
proper way to do this in C#? Thanks.

Jayme
 
C

Clive Dixon

Not quite sure about the finer details of tying it into the collection
Count/Item/_NewEnum methods, but it is easy to implement the standard
IEnumVARIANT interface (the _NewEnum should return an object which supports
IEnumVARIANT):

Give your class a GetEnumerator method a DispId of -4 (your class doesn't
necessarily need to implement IEnumerable, though it can do), and the
generated typelib will contain a method returning IEnumVARIANT

class ComEnumerable
{
[DispId(-4)]
public IEnumerator GetEnumerator()
{
//...
}
}

Generated TLB contains something like (dependent on ClassInterfaceAttribute
settings and what interfaces your class implements)

interface _ComEnumerable : IDispatch
{
[id(0xfffffffc)]
HRESULT GetEnumerator([out,retval] IEnumVARIANT** pRetVal);
}

If you have a more strongly typed enumerator, e.g.

class ComEnumerable
{
[DispId(-4)]
public IStronglyTypedEnumerator GetEnumerator()
{
//...
}
}

you will get something like

interface _ComEnumerable : IDispatch
{
[id(0xfffffffc)]
HRESULT GetEnumerator([out,retval] IStronglyTypedEnumerator** pRetVal);
}

instead.

You could implement both together as follows:

class ComEnumerable : IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
//...
}

[DispId(-4)]
public IStronglyTypedEnumerator GetEnumerator()
{
//...
}
}

so that your class can provide the standard COM IEnumVARIANT enumerator via
the IEnumerable interface plus a strongly typed enumerator. If you implement
IEnumerable you can use this with VB 'for each':

Dim enumerable As mscorlib.IEnumerable

Set enumerable = <your object>



For Each <something> In enumerable


I don't know whether regasm generates anything for the VB collection
interface (which defines Count/Item/_NewEnum) in the same way.
 

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