When using Pinvoke, we are using a machine code dll inside a CLR-based program.
My question is simple, how is it working? How the CLR runs machine code?
How the CLR executes machine code?
480 views Asked by ByoTic At
2
There are 2 answers
0
On
The CLR executes a call
instruction to the native function. The native function does not care what it's caller is as long as the calling convention is being followed.
Before executing the call
instruction there might be work setting up the arguments on the stack and in registers. Nothing of that is fundamentally different from the way a natively compiled program does it.
.NET supports marshalling of complex types such as object references, StringBuilder
, delegates and others. Those are special cases that eventually end up pushing a pointer to the stack (or sending that pointer via a register). Again, nothing fundamentally special compared to native code.
I think you are under the impression that .net programs are executed inside a virtual machine. Whilst it would be, presumably, possible to do that, the well known implementations of .net are not implemented that way.
Rather than using a virtual machine, .net code is compiled to the target machine architecture. Typically this happens in two stages. The main compilation, performed by the developer, compiles to intermediate language, IL. Then, before execution, the just-in-time compiler compiles IL to native machine code. It is the native machine code that executes.
Seen in this light, calling unmanaged code presents no difficulty. A call to a native DLL is not particularly special. There is no virtual machine to escape. The native code is just called directly. Obviously parameters must be marshalled and so on. But otherwise the native code is, from the perspective of the machine, little different from the JIT compiled managed code.