Search code examples
schemeracketbinaryfiles

Save an object to a binary file and retrieve it later


I have following class:

(define stackClass%
  (class object% 
    (super-new)
    (init-field (mystack '(A B C)))      
    (define/public (push n)
      (set! mystack (cons n mystack)))
    (define/public (pop) 
      (cond [(empty? mystack)   #f]
            [else  (define res (car mystack))
                   (set! mystack (cdr mystack))
                   res] ))
    (define/public (get)
      mystack)   ))

I create an object and alter it:

(define sc (new stackClass%))
(send sc push 1)
(send sc push 2)

Can I now save this "sc" object as a binary file to be retrieved later? If yes, would I need to save the stackClass% also? (In reality the objects may be much more complex and may even have other objects, images, files etc, in addition to simple numbers or text).

I checked the documentation at different places including http://docs.racket-lang.org/binary-class/index.html but could not understand how to achieve this.


Solution

  • The racket object system has support for serialization. That means your class must be defined with define-serializable-class and it needs to implement externalize and internalize. externalize needs to return a representation that only consist of serializable data (except instances og its own class) and it seems the system will do the rest. internalize method needs to take that format and set the members on a freshly created instance accordingly.

    Racket seem to add some information so that the rest happens magically as long as the class is defined in the system that unserializes the data.