fslang-suggestions
fslang-suggestions copied to clipboard
Allow 'use ptr = fixed &mem' in computation expressions
Allow 'use ptr = fixed &mem' in computation expressions
I propose we allow pinning locals in computation expressions (CEs) via use ptr = fixed &mem
. This is currently not allowed and results in a confusing error:
Error FS3207 : Invalid use of 'fixed'. 'fixed' may only be used in a declaration of the form 'use x = fixed expr' where the expression is an array, the address of a field, the address of an array element or a string'
Personally I'd like to be able to use it in the result { }
CE.
A workaround is to use the let
-form instead: let ptr = fixed &mem
, which has a couple of problems:
- It's an undocumented form, the docs (and compiler error) state that
fixed
must always be used in theuse
-form. - This form is not allowed outside CEs, this is confusing.
- It's unclear if this unpins the local when going out of scope or not, I wouldn't expect it to. (Testing suggests it does, the generated IL is the same.)
- It doesn't yield an
IDisposable
to dispose manually.
Existings way of approaching this problem in F# are:
- Do the pinning outside the CE (awkward an not always feasible).
- Manual management through e.g.
Marshal.AllocHGlobal
and related functions, preferably made opaque by wrapping it in anIDisposable
type.
Pros and Cons
The advantages of making this adjustment to F# are:
- Less memory management mistakes caused by manual memory management
- Code is more readable
- Less confused F# users
The disadvantages of making this adjustment to F# are:
- I'm guessing there's a good technical reason why it doesn't work at the moment, quoting @dsyme from here:
This is by design for F# 6, because of the way use is de-sugared and treated in computation expressions. Just use a let or similar with a try/finally
I'm not clear if it could be handled differently
Extra information
Estimated cost (XS, S, M, L, XL, XXL): M?
Affidavit (please submit!)
- [x] This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
- [x] I have searched both open and closed suggestions on this site and believe this is not a duplicate
- [x] This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.
Please tick all that apply:
- [x] This is not a breaking change to the F# language design
- [x] I or my company would be willing to help implement and/or test this (I'm not skilled enough to implement this, testing: sure)
For Readers
If you would like to see this issue implemented, please click the :+1: emoji on this issue. These counts are used to generally order the suggestions by engagement.