It is necessary to build database Blob field by using Qbytearray to make it easy to use its API to access and modify memory data. How to write custom structures and classes into blobs
1. Copy memory data with memcpy
Customizing the person structure body
CPP Code
- typedef struct
- {
- int age;
- Char name[20];
- }person;
- Write multiple structures to Qbytearray
- void Writestruct ()
- {
- Qbytearray BA;
- Ba.resize (person); //Set capacity
- //Serialization
- For (int i=0;i<2;i++)
- {
- Person P1;
- P1.age=10+i;
- strcpy (P1.name,"Javaeye");
- memcpy (Ba.data () +i*sizeof (person), &P1,sizeof (person)); //Pointer movement, write multiple data
- }
- //Restore Data
- Person *person= (person*) ba.data ();
- Qdebug () <age<<"---" <name;
- person++;
- Qdebug () <age<<"---" <name;
- }
memcpy can only handle fields as basic type of struct, when using qstring name, I use Person->name to access its value, program crashes; This shows that the memory data cannot be restored and built into the Qstring class. If you want to write a custom QT class, you can only use Qbuffer to write to the binary stream
2. Qbuffer writing QT Custom structure
CPP Code
- Qbuffer Serialization of Custom objects
- typedef struct
- {
- int age;
- QString name;
- }qperson;
- /**
- * @brief overloading the input of custom objects
- */
- Inline Qdatastream &operator<< (qdatastream &out,const Qperson &per)
- {
- out<<per.age<<per.name; < span= "" >
- return out;
- }
- /**
- * @brief overloading the output of custom objects
- */
- Inline Qdatastream &operator>> (qdatastream &in,qperson &per)
- {
- int age;
- QString name;
- in>>age>>name;
- Per.age=age;
- Per.name=name;
- return in;
- }
- /**
- * @brief Qbuffer can handle QT custom types
- */
- void Testqbuffer ()
- {
- Qbytearray BA;
- Ba.resize (Qperson);
- Qbuffer buffer (&BA);
- Buffer.open (qiodevice::writeonly);
- //Input
- Qdatastream out (&buffer);
- For (int i=0;i<2;i++)
- {
- Qperson per;
- Per.age=20+i;
- Per.name=qstring ("sun_%1"). Arg (i+1);
- out<<per; < span= "" >
- }
- Buffer.close ();
- //Output
- Qbuffer buf (&BA);
- Buf.open (qiodevice::readonly);
- Qdatastream in (&BUF);
- For (int i=0;i<2;i++)
- {
- Qperson per;
- in>>per;
- Qdebug () <<per.age<<"---"
- }
- Buf.close ();
- }
Original: http://blog.chinaunix.net/uid-23381466-id-3896956.html
Qt:qbytearray storing binary data (including structs, custom Qt objects)