Browse thread
Marshal and Polymorphism
-
Jonathan Bryant
-
Stephane Glondu
-
Jonathan Bryant
- Stephane Glondu
- skaller
-
Jonathan Bryant
-
Stephane Glondu
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Stephane Glondu <Stephane.Glondu@c...> |
| Subject: | Re: [Caml-list] Marshal and Polymorphism |
Jonathan Bryant wrote:
> Yeah, I'm sorry I wasn't real clear. Let me try again:
>
> This code works:
>
> module Test : [...]
>
> let _ =
> let x = Test.create "Hello" 1 in
> let ser_data = Test.serialize x in
> let deser_data = Test.deserialize ser_data in
> Printf.printf "%s: %d\n" (Test.get_word deser_data) (Test.get_index
> deser_data);
> ;;
>
> My question is: Will this /always/ work (given that the type of data I
> read out of the file is the same)?
It depends on what you mean by "work". Types are not marshaled.
Hence, your deserialize will return ('a, 'b) t (or something like
('_a, '_b) t) in the same way Marshal.from_string returns 'a, which is
meaningless. So you should *always* explicitly give the actual type
(without type variable) when you call deserialize, i.e. your test code
should be:
let _ =
let x = Test.create "Hello" 1 in
let ser_data = Test.serialize x in
let deser_data = (Test.deserialize ser_data :
(string, int) Test.t) in
... ;;
Otherwise, you could write something like:
let _ =
let x = Test.create "Hello" 1 in
let ser_data = Test.serialize x in
let deser_data = Test.deserialize ser_data in
(Test.get_index deser_data) ();;
and get a runtime crash (you wouldn't be able to call "deser_data ()"
directly, though).
> Is it really that simple?
As simple as using Marshal.* functions: if you are aware of the traps...
BTW, here, giving the return type in
(Marshal.from_string x 0 : ('a, 'b) t)
is useless, since it is enforced by the signature.
I hope this will help,
--
Stephane Glondu