1

I'm new with .net(C#).

I need to write an application which gets objects from socket and display it on screen.

The other application which send the messages is not c# (it's c++ if it's matter)

The ICD of the objects is:

int id;
char name[20];
short rates[5]
int lastGrades[10];
  1. How can I define this object in c# ? (It seems that I cant define class with primitve array without using new operator)

I want to do somthing like that to get the message from socket and cast it to my MyObject class.

somthing like:

byte b[] = new byte[100];
socket.Recvive(b);
MyObject myObject = ???cast??? b;
  1. How can I do it ?
  • The application that sends you data serializes the data somehow. Do you know how it's done? Maybe it's just a string or JSON? Or some custom data format. You need to know the format of data. – Andrii Litvinov Mar 15 '17 at 17:30
  • You can write custom operators that can except this cast or place a custom method on your object like public MyObject FromArray() { /* parse the array and return a new MyObject */ } Either way, it's all just 1's and zero's coming from the socket. You have to internally know the schema yourself in order to parse the array out into the a known object. There are tools that help do this like ProtocolBuffers (Protobuf) but they have proven to be more of a problem than a fix. It's easy enough to just parse it if you know what you're parsing. If you don't then you're out of luck. – Michael Puckett II Mar 15 '17 at 17:35
  • 1
    Possible duplicate of [Reading a C/C++ data structure in C# from a byte array](http://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-sharp-from-a-byte-array) – Dweeberly Mar 15 '17 at 17:41

1 Answers1

0

Here is an example for you

public class ICD {

   public int Id { get; set; }
   public string Name { get; set; }
   public short[5] Rates { get; set; }
   public int[5] Grades { get; set; }


   public byte[] Serialize() {
      using (MemoryStream m = new MemoryStream()) {
         using (BinaryWriter writer = new BinaryWriter(m)) {
            writer.Write(Id);
            writer.Write(Name);
         }
         return m.ToArray();
      }
   }

   public static ICD Desserialize(byte[] data) {
      ICD result = new ICD();
      using (MemoryStream m = new MemoryStream(data)) {
         using (BinaryReader reader = new BinaryReader(m)) {
            result.Id = reader.ReadInt32();
            result.Name = reader.ReadString();
         }
      }
      return result;
   }

}
Dmitry Savy
  • 1,067
  • 8
  • 22
  • I think you forgot to add write for Rates and Grades (in the Serialize method) ? –  Mar 15 '17 at 19:36
  • Yes so you would just need to add ReadInt16 depending how many items in array that are defined. See this link for Read options https://msdn.microsoft.com/en-us/library/system.io.binaryreader.readint16(v=vs.110).aspx – Dmitry Savy Mar 15 '17 at 19:39