Win32 COM Collections

Alex Martelli alex at magenta.com
Wed Aug 16 15:55:27 EDT 2000


"Dale Strickland-Clark" <dale at out-think.NOSPAMco.uk> wrote in message
news:MGzm5.11088$t45.379508 at news-east.usenetserver.com...
> (Sorry if this appears twice. It's not showing on my server)
> I need to pass a collection back via COM and I believe I do this by
passing
> back a list of objects? (Please correct me if I'm wrong!)

I think that a list of objects, that you passed back, would be seen
by the COM server as an array (safearray), not as a collection.

A collection is an object; its defining characteristic is that it
implements a method (or property) with dispid DISPID_NEWENUM,
which returns an enumerator (implementation of the interface
IEnumVariants).

So, basically, you have to implement a COM Server Python
object, with the appropriate methods, including one called
_NewEnum which will return the suitable IEnumVariants
implementation.  The easiest way is to import module
win32com.server.util and make use of the ListEnumerator
class it offers -- it implements IEnumVariants on top of
any Python sequence (a list is OK, but so are tuples, or
your own sequence-implementing classes).  You can also
use the ListEnumeratorGateway class if some items on
the list are not-yet-wrapped Python objects.

Easiest way to access either class, in turn, is through
the function NewEnum also made available by that same
util.py module; it returns a properly COM-wrapped
instance of either class (ListEnumerator by default).

Easiest of all, by using the NewCollection function (still from
that same module!) you'll return an instance of the Collection
class (from the same module) which does all of the work
of a typical Collection object on top of a Python sequence
object!  You may want to override (and probably call) some
of its methods if there is something special you want to
do when items get added/read/deleted/etc, or you may
get similar effects by passing your own sequence class.



> How do I implement methods on a collection? For example, to add a new item
> to the collection. Typically this would appear to in the client code as:
>
> collection.add(args)

Since you're implementing the COM server object that is
the collection, you'll also implement the Add, Item, Count,
and whatever other typical collection methods you want.
Those are in fact rather easy!

But win32com.server.util.Collection already implements
Item, Count, Add, Remove, Insert, *and* _NewEnum, so
you may turn out not to have all that much to do!-)

win32com.servers.dictionary is another module you
may want to study (note the PLURAL servers here): it
exposes a Python _dictionary_ a la string-indexed
Collection.  It's rather specialized, but it may be quite
instructive, I think.


Alex






More information about the Python-list mailing list