[Gambas-user] Code for object serialization

Jussi Lahtinen jussi.lahtinen at ...626...
Fri Feb 22 21:28:31 CET 2013


Hi!
This is my implementation for object serialization, it's still bit
incomplete, but it's already usable.
And I thought some of you might find it very useful. I use it now to save
objects to file.

Right now it can handle objects with native datatypes (if you use it
recursively it can be made to handle all types).

What do you think? Is there better way to do this?
Maybe with Object.Address() & Object.SizeOf() ?

Example of how to use it:

'This will save the object to file.

Dim MyObject As MyClass
Dim hFile As File

hFile = Open "~/Desktop/testtest" For Create
SaveValues(hFile, MyObject)
Close #hFile


'This will load the object from file.

hFile = Open "~/Desktop/testtest" For Read
LoadValues(hFile, MyObject)
Close #hFile


And the code itself:

Public Function SaveValues(hStream As Stream, hObject As Object)

Dim hCls As Class = Object.Class(hObject)
Dim sTmp As String

For Each sTmp In hCls.Symbols.Sort(gb.Binary)
  If hCls[sTmp].Kind = Class.Variable Then

    Select Case hCls[sTmp].Type

    Case "h" 'short
      Write #hStream, Object.GetProperty(hObject, sTmp) As Short

    Case "b" 'boolean
      Write #hStream, Object.GetProperty(hObject, sTmp) As Boolean

    Case "c" 'byte
      Write #hStream, Object.GetProperty(hObject, sTmp) As Byte

    Case "i" 'integer
      Write #hStream, Object.GetProperty(hObject, sTmp) As Integer

    Case "l" 'long
      Write #hStream, Object.GetProperty(hObject, sTmp) As Long

    Case "s"
      Write #hStream, Object.GetProperty(hObject, sTmp) As String

    Case Else
      Error.Raise("Error! Missing variable type definition.")
    End Select

  Endif
Next

End

Public Function LoadValues(hStream As Stream, hObject As Object)

Dim hCls As Class = Object.Class(hObject)
Dim sTmp As String

Dim h As Short
Dim b As Boolean
Dim c As Byte
Dim i As Integer
Dim l As Long
Dim s As String

For Each sTmp In hCls.Symbols.Sort(gb.Binary)
  If hCls[sTmp].Kind = Class.Variable Then

    Select Case hCls[sTmp].Type

    Case "h" 'short
      h = Read #hStream As Short
      Object.SetProperty(hObject, sTmp, h)

    Case "b" 'boolean
      b = Read #hStream As Boolean
      Object.SetProperty(hObject, sTmp, b)

    Case "c" 'byte
      c = Read #hStream As Byte
      Object.SetProperty(hObject, sTmp, c)

    Case "i" 'integer
      i = Read #hStream As Integer
      Object.SetProperty(hObject, sTmp, i)

    Case "l" 'long
      l = Read #hStream As Long
      Object.SetProperty(hObject, sTmp, l)

    Case "s"
      s = Read #hStream As String
      Object.SetProperty(hObject, sTmp, s)

    Case Else
      Error.Raise("Error! Missing variable type definition.")
    End Select

  Endif
Next

End


Jussi



More information about the User mailing list