C and C++ are/were often used for providing various code libraries. Examples include:
Sometimes we might want to use these libraries in our projects, but we don’t want to code in C/C++. This is where a technique called “Language Bindings” comes into play. Many languages/runtimes offer a way to run dynamic libraries even if they were compiled from different source languages. For example, in .NET, we can use Platform Invoke. Here’s an example:
What Platform Invoke does is:
- It loads the dynamic library (DLL on Windows) into the memory
- It looks for the specified function
- It arranges arguments of that function on the stack and executes it
- It returns the result
Cairo is a good example of a library that is available only in C. CairoSharp is a language binding for Cairo in .NET C#. It allows .NET programmers to use Cairo in their projects. It has a NativeMethods class that exposes the C functions to the .NET world.
Another good example is GtkSharp, which is a .NET wrapper for GTK toolkit.
Hosting .NET in native code
There is also a way for the reversed operation - running managed .NET code withing a native C/C++ code. It’s explained on MSDN.