我正在尝试编写一个类型来表示GPU设备中的指针,它的行为应该像一个数组,具有get和set的索引属性。如果元素类型是基元类型,则没有问题,但当我使用结构时,我不能更改其成员的值。
请参阅以下代码:
#nowarn "9"
open System
open System.Runtime.InteropServices
[<Struct;StructLayout(LayoutKind.Sequential)>]
type MyStruct =
val mutable x : int
val mutable y : int
val mutable z : int
override this.ToString() = sprintf "(%d,%d,%d)" this.x this.y this.z
let deviceOnly() = failwith "this function should be used in quotation only"
type DevicePtr<'T>(h:nativeint) =
member this.Handle = h
member this.Item with get (idx:int) : 'T = deviceOnly() and set (idx:int) (value:'T) : unit = deviceOnly()
member this.Reinterpret<'T2>() = DevicePtr<'T2>(h)
member this.Volatile() = DevicePtr<'T>(h)
static member (+) (ptr:DevicePtr<'T>, offset:int) = DevicePtr<'T>(ptr.Handle + nativeint(offset * sizeof<'T>))
let test() =
let mutable test1 = MyStruct()
test1.x <- 1
let foo (collection:MyStruct[]) =
collection.[0].x <- 1
let bar (collection:DevicePtr<MyStruct>) =
collection.[0].x <- 1
//error FS0257:
// Invalid mutation of a constant expression.
// Consider copying the expression to a mutable local, e.g. 'let mutable x = ...'.因此,类型是DevicePtr<'T>,它同时具有get和set方法的索引属性项。但是get方法只返回一个值'T,所以我不能改变它。但是系统数组可以工作。
有谁有过这样的经验吗?创建一个类型就像数组一样?我希望索引属性的get函数返回一个可变的ref,而不是一个值。
发布于 2013-04-04 12:32:25
您不能创建使用像数组这样的结构的类型,因为语言和运行时对其他类无法获得的数组进行特殊处理。
对于数组,表达式访问作为结构的元素,就像在foo函数中一样,会导致直接就地修改该元素。collection.[0]有效地设置了一个指向随后应用.x表达式的元素的“指针”或“引用”,允许您就地操作对象。
对于其他类,索引器只是另一个函数,这意味着返回值的副本。因此,在bar函数中,collection.[0]创建返回值的副本,而不是从数组中获得的引用。因为.x将修改临时副本,所以编译器会发出您看到的错误。(对于类似的代码,在C#或VB中也会出现非常类似的警告。)正如消息所暗示的那样,您需要创建一个变量来保存副本,修改副本,然后将其分配回collection.[0]。
https://stackoverflow.com/questions/15802434
复制相似问题