How can I get rid of memcpy in QIoDevice?
-
I'm using Qt to make some audio output. There is an example audioouput, where pure virtual function qint64 QIODevice::readData ( char * data, qint64 maxSize ) is reimplemented like this(this is not actual code from example).
qint64 Generator::readData(char *data, qint64 len)
{
memcpy(data, m_buffer.data(), len);
return len;
}
So, we get pointer to data, copy memory from our buffer to this data. I'm wondering whether I can just assign pointer data to new location, like this:qint64 Generator::readData(char *data, qint64 len)
{
data = m_buffer.data();
return len;
}
Because, memcpy is slow and C. So can I? Thank you!P.S. I'm trying to do it, and I have no sound, so maybe answer is no. Then why?
-
Well, you can assign it just like that, but char *data will now point to m_buffer.data(). I have no idea what m_buffer is, but it's data() member may return a pointer to temporary data that is subject to change, leaving your char *data pointing at bad memory. It all depends on how m_buffer.data() is implemented.
Anyway, the other thing you may be having a problem with is char *. I am assuming since this is sound data it is just bytes. char * is -128 - 127. So by having a signed char you are losing out on any byte that is over 127, which is 128 of them. :) I would change that char *data to unsigned char *data so you don't get cut off bytes. unsigned char would be in the range of 0-255.
Or you could always start using Qt classes for handling byte data like QByteArray. This will do it appropriately and you won't have to worry about memory problems like I pointed out above. Or precision problems like signed vs unsigned data types.
-
m_buffer is QByteArray, and it is class member, so it appears, that m_buffer.data() cannot point to bad memory. Or do you mean, that data() can be strangely realised in QByteArray?
char* data - is in definition of pure virtual function, I cannot change it.
Thank you for reply!
In the example audiooutput they use memcpy, but I just want to do this:
qint64 Generator::readData(char *data, qint64 len)
{
data = m_buffer.data() + m_pos;m_pos+=len; if(m_pos > m_buffer.size()-100000) { m_pos = 0; } return len;
}
I intentionaly added -100000 to prevent out of memory pointer. And all I can hear is noise.