How do I call code written in another language that is not part of .NET, for example the C language?
How does this interaction work?
How do I call native Windows functions?
How do I call code written in another language that is not part of .NET, for example the C language?
How does this interaction work?
How do I call native Windows functions?
Yes. In fact much of .NET interoperates with Win32 or with the API of other operating systems that are provided in C Then it is possible for you to interoperate as well. We're usually talking about working with unmanaged code. Everything that happens in it has no control over the CLR and in general memory allocations must be controlled by this code not having intervention from the garbage collector , so it's a lot riskier. But there is a whole infrastructure to support communication in a simplified way between the managed and unmanaged part.
In fact, it is possible to interact with most of the existing codes in any language as long as these codes meet certain requirements, which have ABI compatible. Any C code interacts well. C was thought of and the operating system, be it Windows, Linux and most others is written or at least has its basic API in C. It is very easy to call C code from .NET and even make some parts of the code. NET can be called in C. One example is SQLite that is written all in C and many people use it as a database embedded in the .NET application.
It is possible to call code in C ++ as well. And I'm not even talking about the C-compatible parts, I'm talking about classes too. There is the C ++ / CLI in the .NET that is a managed C ++ that interacts well with unmanaged C ++. Particularly if I can avoid I prefer, I find the interaction with C much easier. So much is complicated that UWP that is natively written in C ++ uses a slightly different .NET interaction.
Unmanaged code should be segregated in another DLL since they are very different binaries. In .NET Native you do not need to. So you need to load the DLL and create signatures for the functions and available structures in the unmanaged code so that the C # or other .NET language recognizes that function and detects errors. Something like this:
using System.Runtime.InteropServices;
public class Program {
[DllImport("teste.DLL", EntryPoint="print")]
static extern void print(string message);
public static void Main(string[] args) {
print("Chamando C");
}
}
In C:
#include <stdio.h>
void print(const char *message) {
printf("%s", message);
}
I placed GitHub for future reference.