Managed C++ wrappers for legacy C++ libraries

后端 未结 5 1500
挽巷
挽巷 2020-12-14 14:02

We\'re looking at writing a .Net-callable wrapper for some legacy C++ libraries using managed C++.

It all looks pretty easy. Is there anything we need to watch out

5条回答
  •  一向
    一向 (楼主)
    2020-12-14 14:36

    I found it generally quite easy to wrap some existing C++ libraries in C++/CLI and encountered comparatively few pitfalls. The ones I can remember were:

    • Mixing unmanaged C++ code and C++/CLI code in the same executable/DLL is a really bad idea. I've run into problems with competing memory managers at shutdown time that way (basically the .NET runtime and the regular C++ runtime where stepping on each other's toes when it came to cleaning up memory on shutdown, resulting in non-deterministic behaviour as to which one freed what). Instead of linking the static legacy C++ library into the C++/CLI library, I created a DLL containing the legacy C++ and linked that against the C++/CLI DLL, which solved the problem once and for all.
    • If your code is using enums, you have to wrap those in the appropriate C++/CLI enum classes, otherwise other .NET languages won't be able to see and use them.
    • C++/CLI objects can only hold pointers to unmanaged C++ objects. Unfortunately in certain cases, this means you will have to create thin wrapper layers to handle certain objects. My "favourite" was that I had to either wrap boost::shared_ptrs that way (and thus add another layer of indirection) or put them into shared_ptrs with null deleters after crossing the .NET/native boundary. Neither is very nice when you have to deal with APIs that use this sort of construct a lot. RAII doesn't cross this boundary, so be warned, you will have to invest some time into tweaking it to match the .NET way.
    • C++/CLI doesn't do multiple inheritance, so if your legacy library is making use of that you might have to model this using interfaces etc.
    • The internal marshalling code seems to be able to handle most POD conversions, but you'll have find/borrow code that converts std::strings etc. This code is around, a few minutes on Google should bring it up (sorry, don't have any links handy here at the moment).

提交回复
热议问题