4

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?

pad
  • 41,040
  • 7
  • 92
  • 166
cnd
  • 32,616
  • 62
  • 183
  • 313

1 Answers1

5

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.

pad
  • 41,040
  • 7
  • 92
  • 166
  • The same as we did with Date, just use `x.Value`. – pad Oct 31 '12 at 10:02
  • no, I'm getting strange error: This value is not a function and cannot be applied – cnd Oct 31 '12 at 10:06
  • another thing - I can't access Save from C# – cnd Oct 31 '12 at 10:06
  • 'NSL.Packages.Archive' does not contain a definition for 'Save' and no extension method 'Save' accepting a first argument of type 'NSL.Packages.Archive' could be found (are you missing a using directive or an assembly reference?) – cnd Oct 31 '12 at 10:07
  • 1
    1. I can access `x.Value` (see my answer). 2. F# interfaces are explicit, so you need `(instant :> Package).Save()` or propagate the `Save()` method to the upper level in type declaration. – pad Oct 31 '12 at 10:19