cnd
cnd

Reputation: 33764

Adding StructLayout attribute to F# type with implicit constructor

I've got:

type Package =
    abstract member Date : int
    abstract member Save : unit -> unit

[<type:StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)>]
type Instant(date : int, value : int) =
    let mutable _date = date
    let mutable _value = value
    member X.Value : int = _value
    interface Package with    
        member X.Date : int = _date
        member X.Save() = ...

but getting error: Only structs and classes without implicit constructors may be given the 'StructLayout' attribute

so I realize it must be something alike:

type Instant =
    struct
        val Date : byte array
        ...

But this way I lost my interface. In C# for example adding type:StructLayout is possible for this type of classes (I think). How must I refactor my code to avoid this error?

Upvotes: 4

Views: 1098

Answers (1)

pad
pad

Reputation: 41290

As the error message said, StructLayout should work with explicit constructors:

type Package =
    abstract member Date : int
    abstract member Save : unit -> unit

[<type:StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)>]
type Instant =
    val mutable Date: int
    val mutable Value: int
    new(date, value) = {Date = date; Value = value}

    interface Package with
        member x.Date = x.Date
        member x.Save() = x.Value |> ignore

If you have any further problem with FieldOffset, please take a look at code examples here.

Upvotes: 5

Related Questions