CommunityToolkit / CommunityToolkit/dotnet

Proposal: UnsafeHelper class with IL-only As___() methods

Open
#54 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

See this issue I filed here: https://github.com/dotnet/runtime/issues/62342

tl;dr this method would be highly useful, but it's unclear whether it will be approved and added to .NET itself. So, why not put an implementation here in the toolkit?

As for its implementation, it cannot be done in C#. It would have to be via InlineIL.Fody https://github.com/ltrzesniewski/InlineIL.Fody , or as a post-build event that runs a little program using Mono.Cecil to rewrite the IL (all 2 instructions of it!) of the relevant methods.

```
namespace System.Runtime.CompilerServices
{
public static class Unsafe
{
// This name was chosen in part so it does not sort next to other methods like AsRef,
// therefore less probability it could be accidentally used (via auto-complete or etc.).
// sizeof(U) must equal sizeof(T*)
public static ref U AsPtrRef(ref T* source)
where T : unmanaged
where U : unmanaged

// The inverse operation is needed as well, to convert from ref U back to ref T*
public static ref U* AsPtrRef(ref T source)
where T : unmanaged
where U : unmanaged

// Might want to have `ref T**` versions as well, up to a reasonable arity. `ref T***` perhaps, but `ref T*******` is a bit much. `T***` does _very occasionally_ pop up in native interop code (pointer to 2-dimensional array).
}
}
```

@Sergio0694 will probably have a better name for this methods :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.