简体   繁体   English

C#使用非托管数据序列化类

[英]C# serialize class with unmanaged data

I am currently modifying my code so I could serialize it using the built-in .NET Binary serializer. 我目前正在修改我的代码,以便可以使用内置的.NET Binary序列化程序对其进行序列化。 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). 但是,类的一个字段(指向struct的指针)出现了问题,该指针位于非托管内存中(通过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. 看起来.NET只是在序列化时记住指针值,而不是在记住值,而当我反序列化该类时,Matrix属性始终具有随机数据。 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. 提前致谢。

Have your class implement the ISerializable interface and handle the serialization manually as you see fit. 让您的类实现ISerializable接口,并根据需要手动处理序列化。 And don't forget to add the appropriate constructors for deserialization. 并且不要忘记为反序列化添加适当的构造函数。

看一下序列化代理 :当您无法或不想将序列化逻辑与类的业务逻辑(在您的情况下为SparceMatrix)混合时,它们提供了一种实现ISerializable的好选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM