PDA

View Full Version : Converting from char* to QByteArray does not work



kahlenberg
4th February 2016, 16:14
Hello,
I have a char* that holds 256 chars. I can not convert it to QByteArray. My char* contains following data: 0xff, 0xff, 0xff, 0xff, 0xaa, 0x99, 0x55, 0x66, 0x31, 0x61, 0x00, 0x00, 0x32, 0x81,.....


QByteArray b1, b2;
char *data = (char *)malloc(256 * sizeof(char));
FLASH_ReadCalibration(CALIBRATION_ADDR, data);
b1 = QByteArray::fromRawData((const char*)data, sizeof(data));
b2 = QByteArray(reinterpret_cast<const char*>(data), sizeof(data));
emit updateData(ByteData);


b1 and b2 contain only 4 bytes: 0xff, 0xff, 0xff, 0xff

What is wrong with my code?
Thanks.

Added after 25 minutes:

I have found it. sizeof(data) returns 4, although data contains 256 chars.
This worked: b1 = QByteArray::fromRawData((const char*)data, 256);

anda_skoa
4th February 2016, 16:34
I have found it. sizeof(data) returns 4, although data contains 256 chars.

data is a pointer (to char), a pointer's size on a 32bit machine is 32bit (4 bytes), on a 64bit machine 64bits (8 bytes)

For your use case the best apprioach would be to create a QByteArray of the appropriate size and hand its buffer over to the C function.
That avoids copying the data and having to manually free the memory.

Cheers,
_