struct to ubyte[] or ubyte[] to struct for d language
Asked Answered
D

4

5

How the implementation of the struct in the D language to ubyte [] or ubyte [] to the struct, please brothers help answer this question, thank you!

If a struct contains the string or char [] what to do?

For example, such a structure:

struct UserLogin 
{ 
    align(1): 
      ushort ClientId; 
      int AccectId; 
      string LoginUid; 
      string LoginPwd; 
} 

Attention to my application in the socket!

Doreathadoreen answered 25/2, 2012 at 14:24 Comment(1)
For real serialization see the existing answers. Otherwise a reinterpret cast is what you want, something like (cast(ubyte*)var)[0..UserLogin.sizeof]Polemic
H
5

To convert the raw data, the suggested idiom is like this:

struct_type* s = new struct_type;
ubyte[] ub = cast(ubyte[]) s[0..1];
struct_type* s2 = cast(struct_type*) ub.ptr;

This will not handle serialization of strings and pointers, though. You will need to do that manually or with a library.

Hephzipa answered 26/2, 2012 at 1:44 Comment(0)
G
6

I don't think there's anything in the standard library to automatically serialize and deserialize structures to byte streams. std.stream does that for a variety of basic types, but not entire structs. Apache Thrift support is on the way. Among 3rd-party solutions, you can have a look at the Orange serialization library.

Goby answered 25/2, 2012 at 14:31 Comment(1)
I think Orange will make it into phobos.Polemic
H
5

To convert the raw data, the suggested idiom is like this:

struct_type* s = new struct_type;
ubyte[] ub = cast(ubyte[]) s[0..1];
struct_type* s2 = cast(struct_type*) ub.ptr;

This will not handle serialization of strings and pointers, though. You will need to do that manually or with a library.

Hephzipa answered 26/2, 2012 at 1:44 Comment(0)
M
2

@Dev Wolf : You have to write serialization/deserialization yourself. Apart from the Orange mentioned by CyberShadow you also have the Thrift protocol implementation : http://klickverbot.at/code/gsoc/thrift/ . I remember some guys worked on Google Protocol Buffer implementation as well.

Memphis answered 25/2, 2012 at 14:35 Comment(0)
D
0
struct UserLogin
{
  align(1): 
  ushort ClientId; 
  int AccectId; 
  char[10] LoginUid; 
  char[10] LoginPwd; 
}

UserLogin* readByteToStruct = cast(UserLogin*)ne.data;

Will be able to properly take the data...

Doreathadoreen answered 27/2, 2012 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.