Conflicting "unsafe code best practices" information #120095
-
Microsoft's own "unsafe code best practices" says "In CoreCLR, the object header cannot be accessed safely without pinning the object first." Yet, in various low-level regions of the runtime library, you can see the For example: And usage sites that don't "pin" the object: runtime/src/libraries/System.Private.CoreLib/src/System/Array.cs Lines 718 to 761 in 0cbfea4 So which is it? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
I guess it depends on the terminology. All objects in CoreCLR/NativeAOT have the following layout:
So the pointer to the MethodTable is accessible at the offset |
Beta Was this translation helpful? Give feedback.
-
What is disallowed/unsafe for user code is not the same as what is disallowed/unsafe for the runtime itself. User code is written, versioned, and shipped independently of the runtime. It can "roll forward" onto newer runtimes, won't be specially handled by the runtime, and so there are more general limitations to it. The core library (currently Accordingly, one cannot simply look at code in the core libraries and go "they're doing it, so I guess I can in my library as well". |
Beta Was this translation helpful? Give feedback.
-
Also, it's worth noting that the The |
Beta Was this translation helpful? Give feedback.
What is disallowed/unsafe for user code is not the same as what is disallowed/unsafe for the runtime itself.
User code is written, versioned, and shipped independently of the runtime. It can "roll forward" onto newer runtimes, won't be specially handled by the runtime, and so there are more general limitations to it.
The core library (currently
System.Private.Corelib
), however, is "built-in" and ships with the runtime. It is only ever supported with the exact version of the runtime that it was built for and it cannot "roll forward". It, by virtue of being the foundational thing, also provides many specialized types and scenarios which are specially handled by the runtime (VM, JIT/AOT, etc).