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
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.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.
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();
What you could do, is creating a C++/CLI wrapper and expose the functionality of the lib you want to use via your wrapper. The created wrapper dll you can easily reference in your C# project. This of course takes a little bit of work to create the managed/unmanaged wrapper, but will pay off in the long run.
To create a managed C++ project select under the C++ project templates CLR and Class Library. Here you can link to your lib, use the header file the way you are used to.
Next create a new class (ref class) and wrap your library in it. An example might look something like this:
LibHeader.h
int foo(...);
You write a wrapper class like this: Header:
Wrapper.h
public ref class MyWrapper
{
public:
int fooWrapped();
};
Your Implementation:
Wrapper.cpp
#include Libheader.h
int MyWrapper::fooWrapped()
{
return foo();
}
Namespaces and all the good stuff omitted for simplicity. Now you can use MyWrapper in your C# code just as easy as any other managed class. Of course when the interface of the lib gets more complicated you have to think about it a bit more, but it might help to separate the lib-code from your application. Hope to have shed some light on it.
It is 'as hard as it seems'. C++ and C# are ambivalent. The first has deterministic destruction, the second not. Now, you write C++/cli delaying the destruction to some finalizer called by the garbage collector working in it's own thread, introducing problems all over the place (thread safety, are C++ members (used in c++/cli) valid?, ...). Even worse the GC might suggest C++ objects being tiny (a pointer) and provoke a kind of memory leak (due to late deallocating tiny objects). Essentially you end up in writing a GC on top of the C++/cli GC to delete non C++/cli (!) objects in the main thread or another. All that is insane, ...