deniszykov / msgpack-unity3d

MessagePack and JSON serializer for Unity3D
MIT License
102 stars 14 forks source link

"Invalid cast"? #8

Closed endel closed 7 years ago

endel commented 7 years ago

Hey there,

I'm curious why I can't cast a value directly to int? See my REPL output:

> message[4]
53
> (int) message[4]
Invalid cast.
> (uint) message[4]
Invalid cast.
> (byte) message[4]
53

Isn't 53 castable to int?

Cheers!

endel commented 7 years ago

This is really annoying :( when the number grows, it cannot be casted to byte anymore, and neither int, but it works for uint.

> message[4]
85113
> (int)message[4]
Invalid cast.
> (byte)message[4]
Invalid cast.
> (uint)message[4]
85113
deniszykov commented 7 years ago

Hi @endel. You are trying to unbox wrong type. Unbox operation is not 'conversion' to desired type it is 'extraction' value of desired type from object.

MessagePack serializer doesn't preserve number type during serialization/deserialization process. It is inherited from message pack format. For example when you serialize 1024(Int32) it would be written as 0xcd[uint 16] token and deserialized as UInt16.

Easiest approach to workaround this problem is to use Convert.ToInt32 method.

endel commented 7 years ago

Awesome, thanks for the clarification!