I have a code library written in plain old C++ (no .NET/managed code) and I'm porting the application that uses this code to C#. I'm faced with two options:
- Rewrite the C++ code in C# to achieve the same functionality;
- Compile the C++ as a DLL and use it as a library in the C# application.
I'm relatively new to C# and am pretty unfamiliar with the implications of using an unmanaged code library in a C# app (or if there even are any). The code itself is moderate in size; it will likely take only a few days to rewrite in C#, but my thought is that leaving the code as a it is would allow me to use it in other applications as well (and to compile it on UNIX, etc).
What sort of things should I be aware of when making this decision? Are there any major drawbacks or gotchas to using the DLL in the C# application?
It's not necessary to write a wrapper in C++/CLI. You can directly use Platform Invoke from C#:
http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx
EDIT: If you do it using C++/CLI, you'll need to be doing LoadLibrary calls and creating function pointers. This is significantly easier in C#. This is from the MSDN tutorial linked above, but with my own added comments:
EDIT: Complex types can also be marshaled, though it's necessary to define the structs. This example taken from my own code that invokes GDI+. I've snipped it a bit.
I would make a wrapper library using C++/CLI to expose the library to C#. This can leave your library unchanged, and just wrap it for use from .NET, providing the best of both options.
One thing I've found useful is to delve into C++/CLI when dealing with unmanaged C++ libraries. Create a managed wrapper using C++/CLI and call it from your C# code. The managed wrapper can include the library (I assume it's statically linked) in its DLL, and a project reference is all you need for your C# code.