Call c++ library from c#

Batul picture Batul · Jun 2, 2010 · Viewed 11.4k times · Source

This question might seem a repeat of previous ones. I have read through a series of posts, but not completely clear for my situation.

I have a c++ library which is created using momentics IDE. I have to be able to use this library into a c# project.

Someone had been working on this project before being handed over to me. Currently, there are 2 layers for making this possible. First, a c++ project includes the complete library with a c++ wrapper. This project creates a dll as the output. This c++ dll is then fed to a c# project, which has dllimport calls to the c++ dll. This c# project again creates a dll. Finally, in order to use the library in c# application, I have to include a reference to both of these dlls.

Is this the correct way to get it working? I was thinking probably there should be a way to simplify the process.

Can someone please help me with this question?

Answer

Adam Robinson picture Adam Robinson · Jun 2, 2010

Given that you're using a C++ library, I'm assuming it takes advantage of C++ semantics like classes, rather than just exposing procedures. If this is the case, then the way this is typically done is via a manually-created managed C++ interop library.

Basically, you create a managed C++ library in Visual Studio, reference your existing C++ library, and create a managed wrapper around your existing C++ classes. You then reference this (managed) C++ assembly in your C# project and include the original (unmanaged) C++ library in your C# assembly just as a file that gets placed in the build directory.

This is required because there is no way to reference things like C++ classes via P/Invoke (DllImport) calls.

If your base library is just a series of functions, then you can reference that directly in the C# project via P/Invoke functions.

Either way, all of the libraries mentioned above (for the first, the unmanaged C++ library, the managed C++ assembly, and the C# project, or, for the second, the unmanaced C++ library and the C# project) must be included in any project that references them. You cannot statically link the unmanaged library into the managed assembly.