-
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
Unsafe.AsRef cannot be used with ref structs #68709
Comments
Tagging subscribers to this area: @dotnet/area-system-runtime-compilerservices Issue Detailsvoid Foo(in DefaultInterpolatedStringHandler handler)
{
return string.Create(CultureInfo.InvariantCulture, ref Unsafe.AsRef(in handler));
}
|
Hello @Neme12, there is no safe workaround; the |
@teo-tsirpanis But the defensive copy would only happen when calling a non-readonly method on |
BTW I need to use |
In fact, the handler must be passed by ref and must not be copied. It must be mutated to use it correctly. |
@huoyaoyuan |
The problem here is a more fundamental limitation: There is an issue tracking the status on support for using them in generics here: #65112. I would not actually recommend using this, but you can work around the limitation currently by using this awful hack: unsafe string Foo(in DefaultInterpolatedStringHandler handler)
{
var asRef = (delegate*<in DefaultInterpolatedStringHandler, ref DefaultInterpolatedStringHandler>)(delegate*<in byte, ref byte>)&Unsafe.AsRef<byte>;
return string.Create(CultureInfo.InvariantCulture, ref asRef(in handler));
} However, the use case presented here is rather questionable based on your earlier description. Do you have more information about what you're doing? |
@DaZombieKiller Wow, thanks for the workaround! I'm surprised that you can just convert the function to a different one and it works even though I know that not being able to use ref structs as type arguments is the limitation. I was looking either for a workaround that would let me do what
Yes, I know it's hacky and it's an API contract that I violate. I would use a One thing I actually forgot about and didn't account for is that when the method receives a |
DefaultInterpolatedStringHandler
cannot be used as a type argument toUnsafe.AsRef
because it is a ref struct. Is there any workaround for this or any other way to achieve this?The text was updated successfully, but these errors were encountered: