Import a C++ .lib and .h file into a C# project?

Dan James Palmer picture Dan James Palmer · Aug 9, 2013 · Viewed 58.4k times · Source

I have just started a C# project and want to import a C++ .lib and it's corresponding header (.h) file.

I've read various posts that all mention .dll, rather than .lib, which is confusing me.

The image below shows the .lib and .h file I'm referring to, all I've done is drag them into the project.

enter image description here

Can anyone point me to a clearer explanation of how to go about doing this? I'm sure it can't be as hard as it seems.

Answer

Kirk Backus picture Kirk Backus · Aug 9, 2013

This is, unfortunately, a non-trivial problem.

The reason is primarily due to the fact that C++ is an unmanaged language. C# is a managed language. Managed and unmanaged refers to how a language manages memory.

  • C++ you must do your own memory management (allocating and freeing),
  • C# .NET Framework does memory management with a garbage collector.

In your library code

You must make sure all of the places you call new, must call delete, and the same goes for malloc and free if you are using the C conventions.

You will have to create a bunch of wrapper classes around your function calls, and make sure you aren't leaking any memory in your C++ code.

The problem

Your main problem (to my knowledge) is you won't be able to call those functions straight in C# because you can't statically link unmanaged code into managed code.

You will have to write a .dll to wrap all your library functions in C++. Once you do, you can use the C# interop functionality to call those functions from the dll.

[DllImport("your_functions.dll", CharSet = CharSet.Auto)]
public extern void your_function();