f# - F# 4.5 中的 byref 返回

标签 f# byref return-by-reference

我正在尝试向具有 byref 返回方法的类型添加 F# 样式接口(interface)。 代码如下:

type IPool<'P, 'T when 'T: struct> =
  abstract member GetReference: ITypedPointer<'P, 'T> -> byref<'T>

let Ref<'TPool, 'P, 'T when 'TPool :> IPool<'P, 'T>> (pool: 'TPool) pointer =
  pool.GetReference pointer

现在令我惊讶的是,类似的事情运行得很好,直到我引入 IPool界面。在此之前 Ref 本身包含类似 &pool.data.[idx] 的实现,并且工作得很好。

我尝试安装 F# Tools 的 nightly build,因为最新版本不正式支持 byref 返回,并且最近完成了介绍它们的 PR:https://github.com/Microsoft/visualfsharp/pull/4888

但是,我仍然得到 error FS3209: The address of the variable 'copyOfStruct' cannot be used at this point. A method or function may not return the address of this local value.在 Visual Studio 中。类型outref<T>似乎仍然不可用。我错过了什么吗?

我还尝试删除 pointer参数,只需返回 pool.GetReference仅获得不同的错误消息。

加法:最终目标是能够做到

let aref = Ref pool ptr
let bref = Ref pool ptr
aref <- 42
assert(aref = bref)

例如为调用者提供对内部存储器的直接引用,通常由数组支持,类似于 Span<T> 。我这样做是出于性能原因,因此每次调用 Ref 时都进行分配是不行的。

最佳答案

出于某种原因,减少泛化有助于消除错误:

let Ref<'P, 'T when 'T: struct> (pool: IPool<'P, 'T>) pointer = pool.GetReference pointer

解决方案提供者

https://github.com/Microsoft/visualfsharp/issues/5366#issuecomment-407521220

虽然它没有解释为什么原始代码不能编译。

关于f# - F# 4.5 中的 byref 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51033055/

相关文章:

c# - 使用 System.Type 中的泛型类型调用泛型方法

arrays - 经典asp : Function call by reference doesn't work with an array

c++ - 应该重载 operator = 返回 class& 或 class

c++11 - C++11 中返回本地值的最佳方式

f# - 如何为生成的程序集创建 F# 类型提供程序?

.net - 如果随机生成的输入没有用,我如何重新尝试基于属性的测试?

f# - 如何有效地模式匹配?

f# - FParsec:保留行号和列号

vb.net - 传递字符串时的 ByRef 与 ByVal 性能

C++ 返回值、引用、常量引用