Wrapping unmanaged C++ with C++/CLI - a proper approach

女生的网名这么多〃 提交于 2019-11-28 00:03:40

First of all, forget about Managed C++. Use C++/CLI.

The difference is that Managed C++ was Microsoft's first attempt at extending C++ to work with .NET, and honestly, it was all kinds of horrible.

So they gave up on that, and designed C++/CLI instead, which works much better.

Second, valid C++ code should just work if you compile it as C++/CLI, so that does seem like the obvious way to do it.

Of course, in order to expose your C++ types to .NET assemblies, you're going to have to write some wrappers either way. For STL types, you might look into Microsoft's STL/CLR library.

But in general, just add the /cli switch, compile your code as C++/CLI, and then add what wrappers you need. There's no reason why your code would magically become slower or anything.

The way I do it is

  1. Create a normal unmanaged .lib. Make sure that you link to the standard runtime as a DLL (required if the .lib is in an assembly)

  2. Create a C++/CLI assembly.

  3. Add the .lib to the link like of the assembly

  4. Create a managed interface

  5. Minimize the granularity of calls across managed/unmanaged. Meaning, prefer getting big chunks of data (like a datastructure) rather than use an interface to an unmanaged data-structure from the managed side. This is because calls across the boundary are slow.

Things like a std::vector need to be hand-wrapped in System.Collections -- but, "it just works" is good for built-in types and even function pointers.

Other gotchas. Callbacks need to be stdcall to be turned into a delegate, and delgates sent to unmanaged callbacks do not hold a reference (so, arrange to hold a reference somewhere else or crash when the object is GC'd).

If you have a lot of unmanaged functions to wrap, you should consider using SWIG. It writes all the wrapper and interop code for you, and has pre-written SWIG interface files that support std::vector, std::string, windows types, etc.

I have a full example exposing unmanaged C++ DLL functions if you are interested.

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