2

I'm wondering why the IntPtr type is not supported by the XmlSerializer implementation. When I try to serialize a class including a field of IntPtr type, the serialization fails telling me that IntPtr is not supported, and ignore that member.

To workaround this, I translate the IntPtr value to a Int64... but is it a good idea? It should be, as far I can think. In concrete, I need to serialize a window handle, which is typed IntPtr in .NET framework. Am I doing correct?

2
  • Are you planning to deserialize the window handle on the same system, in the same environment? That is, will the window handle still be valid when you deserialize it? Aug 12, 2010 at 22:48
  • Yes, of course. All the system handles could be invalid at every moment (that why SafeHandle class is existing), since they are managed by the system. But this is another topic.
    – Luca
    Aug 13, 2010 at 7:53

2 Answers 2

3

The reason that an IntPtr is not serializable is that it generally doesn't make any sense at all when you remove it from it's environment.

If you serialize a window handle, it only makes sense if you deserialize it in the same spot, while the window still exists. If you deserialize it on a different computer, in a different application, or after the window is removed, the handle has no meaning.

So, you can cast it to a type that is serializable, but it's up to you to make sure that it still makes sense when you deserialize it.

2
  • This argument could be applicable to every information, even a string. For example, a string could specify a shared memory name, and it could be meaningless after serialization. The serialization is able to restore the bit configuration of any object, and it is obvious that an IntPtr has a sequence of bit, that could be serialized as well...
    – Luca
    Aug 13, 2010 at 7:51
  • @Luca: It's of course based on what the data types are intended for, not what they might possibly be (mis)used for.
    – Guffa
    Aug 13, 2010 at 8:53
0

Think of IntPtr as void*. If you want to do anything useful with it, you have no choice but to cast it to something else.

So yes, casting it to int64 in order to serialize it is perfectly reasonable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.