什么是[的DllImport(" QCall")?DllImport、QUOT、QCall

2023-09-02 10:43:00 作者:百鬼夜行.

在NET库

许多方法在本土code实现的。那些来自于框架本身都标有 [MethodImpl(MethodImplOptions.InternalCall)] 。那些来自一些非托管的DLL都标有 [的DllImport] (如 [的DllImport(KERNEL32.DLL)] )。到目前为止,没有什么不寻常。

不过,虽然写回答另一个问题,我发现有标有很多方法[的DllImport(QCall)] 。他们似乎是净的内部实现(如 GC._Collect())。

我的问题是:究竟 [的DllImport(QCall)] 是什么意思?在 [的DllImport(QCall)] [MethodImpl(MethodImplOptions.InternalCall)] 解决方案

这是一个古老的线程。由于CoreCLR现在开源GitHub上;如果有人仍然在寻求答案,这里是official文档:

  

Calling从托管到本机code

     

我们有两个方法调用到来自管理code中的CLR。 FCALL允许你直接调用CLR code,并提供了很大的灵活性操作对象方面,虽然很容易被不正确地跟踪对象引用导致GC孔。 QCall允许你调用到通过P / Invoke的CLR的,而且更容易意外误用比FCALL。 FCalls在管理code确定为extern方法与MethodImplOptions.InternalCall位设置。 QCalls是看起来像普通的P /调用静态外部方法,而是一个名为QCall库。

     

有一个小的变体FCALL叫HCall(用于帮助呼叫)实施JIT助手,做事像访问多维数组的元素,范围检查等HCall和FCALL之间的唯一区别是,HCall方法赢得'T显示在一个异常堆栈跟踪。

然后继续在小标题:

Choosing FCALL,QCall,P / Invoke的,写在管理code之间 QCall功能特性

举例:

QCall示例 - 管理部分 QCall示例 - 未受管理的部分 PMP备考经验 做题方法总结

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)]?

解决方案

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