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

后端 未结 3 945
独厮守ぢ
独厮守ぢ 2020-12-06 12:31

as stated in the title, I want to have my old C++ library working in managed .NET. I think of two possibilities:

1) I might try to compile the library with /clr and

3条回答
  •  执念已碎
    2020-12-06 13:13

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

提交回复
热议问题