Reputation: 2040
Is it possible to take pointer to QByteArray
's internal T* data
and destroy QByteArray
itself so that the pointer remains unreleased? I would like to use it in the something similar to the following scenario:
const char* File::readAllBytes(const String& path, u64& outCount) {
QFile file(*static_cast<QString*>(path.internal()));
outCount = static_cast<u64>(file.size());
if (!file.open(QIODevice::ReadOnly)) gException("Failed to open file");
const QByteArray array = file.readAll();
return array.steal();
}
Upvotes: 1
Views: 1006
Reputation: 98445
No, but you can easily sidestep the problem by not using QByteArray
:
const char* File::readAllBytes(const String& path, u64& outCount) {
QFile file(*static_cast<QString*>(path.internal()));
if (!file.open(QIODevice::ReadOnly)) return nullptr;
auto N = file.bytesAvailable();
char *data = malloc(N);
outCount = file.read(data, N);
return data;
}
The solution above also assumes that the consumer of your data is aware of the need to free
the data.
Alas, the manual memory management called for with such an API is a bad idea. If you wish not to use Qt classes in your API, you should be using std::vector<char>
instead:
std::vector<char> File::readAllBytes(const String& path) {
std::vector<char> result;
QFile file(*static_cast<QString*>(path.internal()));
if (!file.open(QIODevice::ReadOnly)) return result;
result.resize(file.bytesAvailable());
auto count = file.read(result.data(), result.size());
result.resize(count);
return result;
}
I smell that String
is some sort of a framework-independent string wrapper. Perhaps you could settle on std::u16string
to carry the same UTF16 data as QString
would.
Upvotes: 0
Reputation: 40502
No, you can't steal QByteArray
's pointer unless it has been constructed with QByteArray::fromRawData
, which is not the case. However you can create char array manually and read data from file to it using QFile::read(char * data, qint64 maxSize)
. You will then decide where to pass the pointer and when to delete[]
it.
Note that this is not considered good practice. You should use managed allocations whenever you can, and Qt provides enough to cover most of possible use cases. You should not do this unless you're trying to do something really low-level.
Note that many of Qt classes, including QString
and QByteArray
, use copy-on-write strategy, so you generally should not be afraid of copying them and passing them to another context.
Upvotes: 3