-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
UnsafeAccessor does not work for generic constructors, .NET 9 #110054
Comments
Where using System;
using System;
using System.Runtime.CompilerServices;
Hack<int>.CreateBar();
Bar<int> evil = (Bar<int>)RuntimeHelpers.GetUninitializedObject(typeof(Bar<int>));
Console.WriteLine(Hack<short>.CreateBar());
Hack<int>.HacketyHackHack(evil);
Console.WriteLine(evil);
static class Hack<T>
{
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = ".ctor")]
internal extern static void HacketyHackHack(Bar<T> obj);
[UnsafeAccessor(UnsafeAccessorKind.Constructor)]
internal static extern Bar<T> CreateBar();
}
class Bar<T>
{
private readonly string s = ".ctor has run; " + typeof(T).Name;
public override string ToString() => s;
private Bar() { }
} |
Useful workaround @vcsjones ! (I haven't verified, but will do tomorrow) |
@mgravell This isn't a "workaround", it is how the feature works. See the following comment in the Remarks section of the documentation.
In your example the Please let me know if the documentation could be updated to help clarify things. |
Ok, this is reader error. There's even examples. I personally didn't find the exception cear, but I can't say that it is incorrect. Thanks for the assist. |
We can't add analyzers about it because of reference assemblies, but I wonder if a build tool that has a whole-program view like ilc or crossgen could warn that an unsafe accessor does not have a valid target. |
Yes it can. It is what native AOT does for this scenario and should warn. Note that |
Native AOT compilation does not and should not warn when the |
Description
This ticket suggests that this should work from 9.0 Preview 4, however this fails in 9.0 GA:
Reproduction Steps
as above
Expected behavior
it works
Actual behavior
Unhandled exception. System.InvalidProgramException: Generic type constraints do not match. at Hack.CreateBar[T]() at Program.<Main>$(String[] args) in C:\Users\marcg\source\repos\ConsoleApp4\ConsoleApp4\Program.cs:line 7
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response
The text was updated successfully, but these errors were encountered: