Dimitar Vouldjeff
Dimitar Vouldjeff

Reputation: 2107

C# serialize class with unmanaged data

I am currently modifying my code so I could serialize it using the built-in .NET Binary serializer. However a problem occured with one of the class`s fields - a pointer to struct, which is in the unmanaged memory (created via p/invoke). It appears that .NET just remembers the pointer value while serializing, rather than the values, and when I deserialize the class the Matrix property has always random data. Below you could find a sample of my code:

[Serializable]
public unsafe class FrequencyMatrixBuilder
{
    public SparseMatrix* Matrix { get; private set; }
    ....
}

[Serializable]
[StructLayout(LayoutKind.Sequential)]
public unsafe struct SparseMatrix
{
    public int rows;
    public int cols;
    public int vals;
    public int* pointr;
    public int* rowind; 
    public double* value;
};

Any suggestions how can I resolve this problem? Thanks in advance.

Upvotes: 2

Views: 866

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

Take a look at serialization surrogates: they provide a good alternative to implementing ISerializable when you cannot or do not want to mix serialization logic with the business logic of the class (in your case, SparceMatrix).

Upvotes: 1

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

Have your class implement the ISerializable interface and handle the serialization manually as you see fit. And don't forget to add the appropriate constructors for deserialization.

Upvotes: 3

Related Questions