Serializing IronPython Objects Which Inherit From CLR Types
This may be a bit of a weird question, but is there any reliable way to serialize IronPython objects whose classes extend CLR types?
For instance:
class Foo(System.Collections.Generic.List[str]):
def Test(self):
print "test!"
System.Collections.Generic.List<string>
is serializable with Pickle, as it implements the ISerializable
interface, but emitted subclasses of serializable CLR types seem to not work, and i get ImportError: No module named Generic in mscorlib, Version=4
when running pickle.dumps(Foo())
.
Additionally, running the usual Formatter.Serialize(stream, object)
gives me:
SystemError: Type 'IronPython.NewTypes.System.Collections.Generic.List`1_4$4' in Assembly Snippets.开发者_如何学Pythonscripting, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
How can I implement serialization of IronPython objects when running in an embedded C# environment?
I don't know if it is what you are after, but you could consider the python version of protobuf (here)? I haven't tested it specifically on ironpython, mind. This has the added advantage that there are also C# implementations that may help, while keeping it platform independent. When possible I want to get protobuf-net to support DLR types, but that is a big job.
As a side note, personally I'd recommend having a dedicated DTO type rather than trying to extend the inbuilt types.
Quote from clrtype metaclasses
IronPython doesn’t support Reflection based APIs or custom attributes today because IronPython doesn’t emit a custom CLR types for every Python class. Instead, it typically shares a single CLR type across many Python classes. For example, all three of these Python classes share a single underlying CLR type.
class shop(object):
pass
class cheese_shop(shop):
def have_cheese(self, cheese_type):
return False
class argument_clinic(object):
def is_right_room(self, room=12):
return "I've told you once"
import clr
print clr.GetClrType(shop).FullName
print clr.GetClrType(cheese_shop).FullName
print clr.GetClrType(argument_clinic).FullName
Even though cheese_shop inherits from shop and argument_clinic inherits from object, all three classes share the same underlying CLR type
I haven't tried, but maybe you can solve this issue with manual serialization via serialization surrogates.
精彩评论