Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is [DllImport("QCall")]?

Many methods in the .Net library are implemented in native code. Those that come from the framework itself are marked with [MethodImpl(MethodImplOptions.InternalCall)]. Those that come from some unmanaged DLL are marked with [DllImport] (e.g. [DllImport("kernel32.dll")]). So far nothing unusual.

But while writing answer for another question, I discovered there are many methods marked with [DllImport("QCall")]. They seem to be internal implementation of .Net (e.g. GC._Collect()).

My question is: What exactly does [DllImport("QCall")] mean? What is the difference between [DllImport("QCall")] and [MethodImpl(MethodImplOptions.InternalCall)]?

like image 782
svick Avatar asked Feb 28 '12 23:02

svick


2 Answers

I asked some people in the .Net team about this.

QCalls are calls to native methods within the CLR runtime. They behave like other [DllImport]s, but they're faster because they make specific (undocumented) assumptions about what the native methods do, so they can skip various marshalling and GC and exception checks.

InternalCall is different; it's for calls for special reflection-style things which are generated at runtime (this wasn't very clear).

like image 152
SLaks Avatar answered Nov 11 '22 16:11

SLaks


This is an old thread. Since CoreCLR is now open-sourced on GitHub; if someone is still seeking the answer, here is the official documentation:

Calling from managed to native code

We have two techniques for calling into the CLR from managed code. FCall allows you to call directly into the CLR code, and provides a lot of flexibility in terms of manipulating objects, though it is easy to cause GC holes by not tracking object references correctly. QCall allows you to call into the CLR via the P/Invoke, and is much harder to accidentally mis-use than FCall. FCalls are identified in managed code as extern methods with the MethodImplOptions.InternalCall bit set. QCalls are static extern methods that look like regular P/Invokes, but to a library called "QCall".

There is a small variant of FCall called HCall (for Helper call) for implementing JIT helpers, for doing things like accessing multi-dimensional array elements, range checks, etc. The only difference between HCall and FCall is that HCall methods won't show up in an exception stack trace.

And then it continues in subheadings:

  • Choosing between FCall, QCall, P/Invoke, and writing in managed code
  • QCall Functional Behavior

with examples:

  • QCall Example - Managed Part
  • QCall Example - Unmanaged Part
like image 21
vulcan raven Avatar answered Nov 11 '22 16:11

vulcan raven