1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
// Dans une dll 1
[Serializable]
public ref class A sealed : public ISerializable
{
public:
// ...
virtual void GetObjectData(SerializationInfo ^info, StreamingContext context)
{
// On ajoute les valeurs des instances A à sérialiser ici
info->AddValue("value", values);
}
};
// Dans une Dll 2
[Serializable]
public ref class B sealed : public ISerializationSurrogate
{
public:
// ...
A ^pA;
// Normalement appelée lors de la sérialisation
virtual void GetObjectData(System::Object ^obj, SerializationInfo ^info, StreamingContext context)
{
B ^b = (B^) obj;
info->AddValue("B::pA", b->pA, A::typeid);
}
// Normalement appelée lors de la désérialisation
virtual System::Object ^SetObjectData(System::Object ^obj, SerializationInfo ^info, StreamingContext context, ISurrogateSelector ^selector)
{
B ^b = (B^) obj;
b->pA = (A^) info->GetValue("B::pA");
return obj;
}
};
generic <typename T>
void fctSerialize(String ^filename, T instance)
{
IO::StreamWriter ^writer = gcnew IO::StreamWriter(filename);
Runtime::Serialization::Formatters::Binary::BinaryFormatter ^bf = gcnew Runtime::Serialization::Formatters::Binary::BinaryFormatter;
bf->Serialize(writer->BaseStream, instance);
writer->Close();
}
generic <typename T>
T fctDeserialize(String ^filename, T instance)
{
IO::StreamReader ^reader = gcnew IO::StreamReader(filename);
Runtime::Serialization::Formatters::Binary::BinaryFormatter ^bf = gcnew Runtime::Serialization::Formatters::Binary::BinaryFormatter;
instance = static_cast <T> (bf->Deserialize(reader->BaseStream));
reader->Close();
return instance;
}
// Dans mon appli
int main(...)
{
B ^b; // avec initialisation de l'instance pA
// ...
fctSerialize("filename", b);
// on redémarre l'appli et on désérialise pour le test
b = fctDeserialize("filename", b);
} |
Partager