-
Notifications
You must be signed in to change notification settings - Fork 4.1k
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
Error clarity: Cannot pass stack allocated spans to instance methods on ref struct #23433
Comments
Tagging @VSadov |
Ping @VSadov |
This is ByDesign as we have discussed. Either the struct must be Otherwise nothing stops the method from doing |
It would be nice if I could somehow indicate I won't store the buffer in a field, e.g.: public void Bar(Span<byte> buffer) readonly {
Console.WriteLine(buffer.Length);
} |
Individually readonly members could help too. As long as one knows what is wrong. |
Another idea (from @pakrym) would be to simply allow calling such members as long as they are marked unsafe: public unsafe void Bar(Span<byte> buffer) {
Console.WriteLine(buffer.Length);
} |
@KrzysztofCwalina Since this is currently by-design, I'll go ahead and close this issue. |
I'm trying to implement a public unsafe ref struct SpanWriter
{
// private ...
public bool TryAppend(ReadOnlySpan<byte> data)
{
// ...
}
} I guess I can't workaround this since I don't want to make my struct |
@tmd, I think you can workaround this by changing the method to a static method. public static bool TryAppend(SpanWriter writer, ReadOnlySpan<byte> data)
{
// ...
} |
For the benefit of others who come across this: Problem with the workaround above is that the method presumably has to modify a position field within the SpanWriter, or maybe replace the span it holds with a slice of the unwritten portion. So it either has to be a non-readonly instance method or take the instance byref, either way getting CS8350. Another workaround, if you know the implementation will not save the span and only copy from it, is to trick the compiler by recreating it: TryAppend(MemoryMarshal.CreateReadOnlySpan(ref MemoryMarshal.GetReference(span), span.Length)); // No CS8350 Obviously this is unsafe. |
I ran into this trying to make an extension method on |
I bumped into this issue when doing prototyping work for dotnet/runtime#54410. It would be nice if we could somehow indicate that the buffer will never be stored in the ref struct, even if it means marking the method as unsafe. |
Version Used:
7.2
Steps to Reproduce:
Expected Behavior:
The program should compile fine (possibly with some modifications/annotations.
Actual Behavior:
Error CS8350 This combination of arguments to 'Foo.Bar(Span)' is disallowed because it may expose variables referenced by parameter 'buffer' outside of their declaration scope ConsoleApp5 C:\Users\Krzysztof\Documents\Visual Studio 2017\Projects\ConsoleApp5\ConsoleApp5\Program.cs 9 Active
The text was updated successfully, but these errors were encountered: