1

I have a simple class object with a specific set of data in itcl.

package require Itcl
itcl::class myDataSet {
    public variable var1 "data1"
    public variable var2 "data2"
    public variable var3 "data3"

    method setVals { v1  v2 v3 } {
        set var1 $v1
        set var2 $v2
        set var3 $v3
    }
}

myDataSet dataObj1
dataObj1 setVals "1" "abc" "1.23"

Is there a way we can write a itcl objects directly into a external file as we do it in C?

Something like,

set fPtr [open "myStorageFile" "w"]
puts $fPtr dataObj1
close $fPtr
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Ashwin
  • 993
  • 1
  • 16
  • 41
  • Object are not directly serializable; they could contain references to things like file descriptors which can't be _meaningfully_ written out. You have to ask an object to serialize itself so that you can rebuild it later on. What version of [incr Tcl] are you using? – Donal Fellows Mar 23 '15 at 09:08
  • I am using 8.5.7 of Tcl, Itcl version 3.4 – Ashwin Mar 23 '15 at 09:40

1 Answers1

2

The simplest way to do this is to give each class a “write yourself to a channel” method, where the serialization format is a Tcl script. Since you've got a method to set all the values, this is easy:

method saveYourself {channel} {
    puts $channel "if {\"$this\" ni \[[list info commands $this]\]} {"
    puts $channel [list [$this info class] $this]
    puts $channel [list $this setVals $var1 $var2 $var3]
    puts $channel "}"
}

Which you'd call like this:

set fPtr [open "myStorageFile" "w"]
dataObj1 saveYourself $fPtr
close $fPtr

Loading the object back in is then just a matter of sourceing the file that you wrote those out to. Note that I was careful to use list to build the commands to create the object, and that it doesn't overwrite the object if it already exists.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215