Closed mgravell closed 4 minutes ago
Where T
is declared seems to matter. This works:
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)
cc @AaronRobinsonMSFT
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.
Generic parameters are supported since .NET 9. Generic parameters must match the target in form and index (that is, type parameters must be type parameters and method parameters must be method parameters).
In your example the T
for Bar<>
is a type parameter, but in HacketyHackHack<T>(Bar<T> obj)
and CreateBar<T>()
, T
is a method parameter. The approach demonstrated in the documentation and in https://github.com/dotnet/runtime/issues/110054#issuecomment-2491839967 makes the T
a type parameter and therefore the look-up works.
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.
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
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response