TransWikia.com

How to separate "unmanaged" and "managed" code in my C++/CLI project

Software Engineering Asked by Simon H on January 31, 2021

I am developing a project using C++/CLI and WinForms. It is a geometry project, which is why I have to use C++/CLI, because of the C++ geometry library CGAL. I chose to use WinForms for the UI because compared to the other C++/CLI windows UI options it seemed rather easy to use. However, after some research online I realized that WinForms for C++/CLI makes use of managed code and that managed code is oftentimes a factor 2 slower than native code. The project is about implementing a competitive algorithm, so the running time is very important. The project will have a very simple UI form to select some parameters for the project and the running time will only be tracked for the actual computation part of the project, not for the UI interaction.

Will using WinForms, in this case, slow down the running time of the geometrical computations? Or is it okay, because the geometrical part of the code is in an "unmanaged" part. How can I make sure that it is "unmanaged"?

One Answer

C++/CLI allows to mix managed and unmanaged Code within the same DLL/EXE ("assembly"). In laymans terms, a "managed" class starts with the ref class keyword, an unmanaged class is introduced without the ref keyword.

In the scenario described in the question, one will usually implement the program using (at least) three layers:

  • an unmanaged C++ layer which contains the core algorithms

  • an UI layer, probably written in C#, since the WinForms designer works best with that language

  • an intermediate managed C++/CLI layer as a "middleman" which connects the former two, and provides a managed API for the UI to access the unmanaged layer.

That way, the unmanaged layer will benefit from the full optimization capabilites of the native C++ compiler. It should be obvious one should avoid callbacks to managed functions from within the performance critical sections of the program.

If the "unmanaged layer" is part of the same assembly where the managed C++/CLI code is placed, or if it is placed in a separate lib or dll does usually not make a big difference for the performance. Technically, both approaches are possible.

Thanks to @rwong for pointing out in a comment that it might be necessary to put #pragma unmanaged into to the unmanaged C++ class files, in case one is not going to use separate libs.

Answered by Doc Brown on January 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP