Cysharp / PrivateProxy

Source Generator and .NET 8 UnsafeAccessor based high-performance strongly-typed private accessor for unit testing and runtime.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Backport to older .NET versions with IgnoresAccessChecksToAttribute?

BlinD-HuNTeR opened this issue · comments

Even though UnsafeAccessorAttribute is new to .NET 8, accessing private members with no overhead has always been possible in older .NET runtimes through the use of IgnoresAccessChecksToAttribute. That are a couple of NuGet packages (like MakeTypesPublic) that provide MSBuild targets to automate all steps required to use it.

My suggestion is that, it would be very nice if the Source Generator could provide a fallback, and generate proxies that use this attribute instead, when building in .NET versions where UnsafeAccessorAttribute is not available.

Unfortunately, though, you can't use IgnoresAccessChecksToAttribute to unlock access inside your own assembly. But I suppose if someone wants that, they can just edit their own source code and make things internal, so this shouldn't be an issue.

I don't see how IgnoresAccessChecksTo would work in at all the same model as this source generator.
It would require a different assembly to be generated that includes the attributes and the code to call the private code.

AFAIK IgnoresAccessChecksTo can only be meaningfully used by IL emitting generators (i.e. dynamic code gen) because the C# compiler itself does not honor it. Even if you have a C# project that includes this attribute, C# won't let you access the private members. I use this attribute myself, but only when the C# compiler doesn't apply, because I'm emitting IL directly.

AFAIK IgnoresAccessChecksTo can only be meaningfully used by IL emitting generators (i.e. dynamic code gen) because the C# compiler itself does not honor it.

It's true that the compiler does not honor it, but it's possible to compile your code against publicized asemblies, so that all members appear as public at compile-time (at runtime you use the original assemblies, and the attribute will do its work).

The NuGet package I mentioned uses MSBuild targets to automatically generate such publicized assemblies and reference them in your project. This way it's possible to have a source-based approach.