Wrapping an Unmanaged C++ Class Library with C++/CLI - Question 2 - Collections

拜拜、爱过 提交于 2019-12-04 06:03:08

This is a very hard question to answer, but I am going to suggest that you have a marshalling/conversion layer that converts from managed collections to unmanaged ones. Keep your library exactly as it is, and just convert the parameters and returns.

This is what I would do if

  1. The collections aren't giant
  2. They aren't constantly passed back and forth all of the time.
  3. You often get the collection in the client code and then do a bunch of calls on it completely in managed land.

For these reasons

  1. It layers the API keeping it simpler
  2. crossing the unmanaged/managed boundary can be a bottleneck and should be minimized

This would be my default approach unless I really needed access to the functionality of the lib in the datastructure (it wasn't just organized data -- but data and behavior)

Ben Voigt

Lou has an excellent suggestion and I agree with his conditions on when that approach is good.

If instead the collections are very large, or are passed back and forth frequently, you'd be better off implementing the .NET enumerable interface but not using .NET collections. Basically, you'd have a collection wrapper that owns a native STL collection, and an iterator wrapper that owns a native STL iterator. The collection wrapper would implement the IEnumerable interface and GetEnumerator would create an instance of the iterator wrapper, the iterator wrapper would implement the IEnumerator interface.

You'd want to make yourself a helper managed class (probably a value class) that wraps the pointer to the native collection and does reference counting, like boost::shared_ptr. Use stack semantics notation to make sure that the reference counting gets done automatically when the managed collection wrapper or iterator wrapper get disposed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!