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
Volatile and atomic operations on unmanaged memory (native pointer dereference, strong type checking) #409
Comments
Looks like I found a way to make an NativePtr helper: module NativePtrExtension = begin
[<NoDynamicInvocation>]
let inline toByref (x: nativeptr<'T>) = (# "" x : 'T byref #)
end let ptr = Marshal.AllocHGlobal(sizeof<int32>) in
Marshal.WriteInt32(ptr, 0);
let mutable intPtr = NativePtr.ofNativeInt ptr
System.Console.WriteLine("Old Value: {0}", Marshal.ReadInt32(ptr));
let pOld = Interlocked.CompareExchange(NativePtrExtension.toByref intPtr, 1, 0);
System.Console.WriteLine("New Value: {0}", Marshal.ReadInt32(ptr)); The generated IL looks like this:
|
Yes, this looks ok, I'll close this as a workaround unless we hear otherwise. |
This was referenced Oct 4, 2017
16 tasks
5 tasks
This was referenced Jul 20, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would like to be able to do volatile and atomic operations on unmanaged memory from .NET in F#. However it seems that there is no way to express the same operations in F# due missing pieces.
The original issue comes from:
https://github.com/dotnet/coreclr/issues/916
Based on the provided example I created sample program in C# which looks working:
https://gist.github.com/zpodlovics/6f4195441f88f01cd0b3
I created a helper method in C# to figure out how the void* type is represented in F# which looks like nativeptr in F# and int32* type looks like nativeptr in F#.
The CompareExchange call IL looks like this:
Typed ptr version:
The CompareExchange call IL looks like this:
F# implementation (without the pointer dereference)
I also tried with
nativeptr<int32>
The closest thing I found in the documentation for dereference is the NativePtr.read but this will copy the value from the ptr to a new variable.
https://msdn.microsoft.com/en-us/library/ee353827.aspx
The output will be:
Instead of:
Maybe I miss something but it seems that I cannot express the same operations in F#. Is there any way to express a pointer dereference in F#? Is there any way to express the same operations in F# that is available in the C# sample?
The text was updated successfully, but these errors were encountered: