Custom IO Device

From Qt Wiki
Revision as of 15:13, 14 January 2015 by Maintenance script (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Writing a Custom I/O Device

This is a port of the article in Qt Quarterly 12 about writing a custom QIODevice [doc.qt.nokia.com]

Usage:

The following code snippet shows how we would use the custom I/O device to encrypt data and store the result in a file:

And on the possible usage (in our example code in git qtdevnet-wiki-mvc/qtdevnet-custom-iodevice [gitorious.org])

Encryption

Decryption

Example image of the test app:

Test app

The Custom I/O Device

Writing a custom QIODevice class in Qt 4 involves inheriting QIODevice and then reimplementing a set of virtual functions.

There is a big difference regarding writing a custom IO device compared to Qt 3: you only have to rewrite 2 functions:

  • qint64 QIODevice::readData ( char * data, qint64 maxSize )
  • qint64 QIODevice::writeData ( const char * data, qint64 maxSize )

Our CryptDevice class will be a sequential I/O device. Whether it’s synchronous or asynchronous depends on the underlying QIODevice.

Source Code

The class definition looks like this:

The constructor definition is pretty straightforward

As our device should be sequential, we re-implement isSequential

In

open()

, we open the underlying device if it’s not already open and set the device state to mode.

Closing is trivial.

When reading a block, we call

read()

on the underlying device. At the end, we XOR each byte read from the device with the magic constant 0×5E. When writing a block, we create a temporary buffer with the XOR’d data. A more efficient implementation would use a 4096-byte buffer on the stack and call

write()

multiple times if size is larger than the buffer.

Categories: