We have legacy C++ code performing high-performance data processing (e.g., large volumes of data fed from hardware devices that is processed in a time-sensitive manner for display, transforms, and transfer to secondary storage).
We are interested in C#/.NET for new GUIs and new utilities (existing GUIs are C++ MFC and Qt). Of course, with the existing system we have no “language translation” issue to the .NET virtual machine (existing code is all C++).
After much study, and many books, I’m not sure this can be done effectively. Possible approaches (am I missing any?):
- Rewrite everything in .NET (can’t
happen — too much code, bare-metal device access, time-sensitive heavy algorithm processing) - Thin adapter layer for Managed
C++/CLI - Thick adapter layer for Managed
C++/CLI - Don’t use .NET (managers feel great
sadness)
Our concerns about (2) “thin adapter layer” is that it would be nice if the GUIs could (re-)use the logic in the “business” layer (many properties are algorithmically derived), so if we don’t expose/wrap the C++ classes, much GUI logic will merely replicate the existing C++ logic in the business layer.
Our concerns about (3) “thick adapter layer” is that it seems very tedious (expensive) to wrap each C++ class with a C# class, and several books suggest the boxing/unboxing access across that boundary appear to suggest this approach is quite unworkable/prohibitive (it’s performance prohibitive beyond trivial designs).
How would you interface new C#/.NET (GUI) on top of a deep-rich-class-structure implemented in C++?
C++/CLI is perfect for this. There are no performance issues with the managed/unmanaged translation, since C++/CLI uses the same optimized call technique used by the .NET runtime engine itself to implement high-performance methods such as string concatenation.
The performance problems arise when you’re copying data back and forth between .NET and native versions of the same data structure, but you’d have the same problem with e.g. using a library that uses BSTR alongside one that uses
std::string, and the slow operations are equally obvious (unlike with P/Invoke, which tries to make these translations transparent, and ends up hiding the performance problems in the process).There are also some tricks you can use to overcome this. For example, instead of copying a
std::vectorinto aSystem::Collections::Generic::List, implement anIEnumeratorthat directly reads from thestd::vector.And of course, if the data is simply going to be passed directly back to another C++ function, there’s no reason to convert it to a managed type at all. Again, C++/CLI makes preserving the format easy, where P/Invoke tries to convert everything behind your back.
In summary, the “thin” C++/CLI wrapper layer is the best of your options.