COM Interop Dance: To C++ or C#

So there’s a managed class that I’m using from within native code via COM Interop.  The managed class has a property that’s a bit like a collection; it stores multiple elements and can retrieve an element by it’s position within the collection.

Each element has an integral ID and a string descriptor.

The problem is that I now need to access these elements from within native code in a certain order (integral ID ascending).

A few approaches come to mind:

  1. Do the sort in native code.  Create a structure that stores the ID, Desc pair OR get a little more fancy and use an STL class.  Store these in a collection (or array).  With the STL class writing the code to sort the collection is more elegant (e.g., easily adapted to different element types) but ultimately I’ll still need to write what is essentially a function that the sort function will use to compare elements.
  2. Do the sort in managed code.  Since this is COM Interop, provide a method that returns a collection of the IDs in order then use the existing method to get the Desc for a given ID.  The collection can be accessed in native code via the smart pointer mscorlib::_ArrayListPtr.  This is probably easier to write but still doesn’t match what I think is conceptually the correct solution.
  3. Provide an enumerator over the collection of ID-Desc pairs.  This will require both managed and native code changes since there’s a little bit of plumbing to use a managed enumerators from C++ (no handy built-in foreach).  In pre 2.0 C# I’d say that this is the correct solution.
  4. Provide an iterator over the collection of ID-Desc pairs.  I think this is closest to the conceptually “ideal” solution.  Unfortunately I have no idea how to use iterators from native code.  And time is extremely short.

Since time is so extremely short I think I’ll go with option 2.  I spend more time in managed space (usually, though for the past month this hasn’t been true) so there’s less ramp up to making this work.

No comments:

Post a Comment