CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2004
    Posts
    8

    Question how to read a struct block from a file?

    there is a Binary stream file from A/D ,its format is fixed by known struct ,like this:

    {
    int i1;
    short i2;
    float i3;
    char[] i4; //size of array is 24
    int i5;
    ...
    int in;
    }

    i can read it with a struct p in c++ like this:
    file.Read(&p,size(p);

    you know, in c# ,it may be read with class Serialization method, but it will produce an error."...mscorlib.dll error...BinaryFormatter version incompatible...."

    how can i read this struct in c#?

  2. #2
    Join Date
    Jul 2003
    Posts
    54
    When you declare

    char[] i4;

    That means compiler can not know what size of array, so it could not read a block. Your struct is an managed code. So you must code it yourself.

  3. #3
    Join Date
    Mar 2004
    Posts
    8
    thx!

    can you give me an example?

  4. #4
    Join Date
    Jul 2003
    Posts
    54
    Instead of define a struct, you define a class in C# and implement the ISerializable interface for that class. So anytime when you serializing or deserializing, you just need to call only one line of code.

    Example :

    [Serializable]
    public class AAA : ISerializable
    {
    public int nAAA = 0;
    public byte[] caGiday;
    public int nBBB = 0;

    public AAA()
    {
    }

    public AAA(SerializationInfo info, StreamingContext context)
    {
    nAAA = info.GetInt32("nAAA");
    caGiday = new byte[24];
    for (int i = 0; i < 24; i++)
    caGiday[i] = info.GetByte("caGiday"+i.ToString());
    nBBB = info.GetInt32("nBBB");
    }

    public void GetObjectData(SerializationInfo info,
    StreamingContext context)
    {
    info.AddValue("nAAA", nAAA);
    for (int i = 0; i < 24; i++)
    info.AddValue("caGiday"+i.ToString(), caGiday[i]);
    info.AddValue("nBBB", nBBB);
    }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured