Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

.net - Managed C++ wrappers for legacy C++ libraries

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 for?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...