将二进制数据从 QML 传递到 C++ [英] Pass binary data from QML to C++

查看:51
本文介绍了将二进制数据从 QML 传递到 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 QML 中的 JavaScript 中有一个二进制字符串",表示我想传递给 C++(通过已建立的套接字发送)的原始字节.

I have a 'binary string' in JavaScript inside of QML, representing raw bytes that I want to pass to C++ (to send over an established socket).

我使用的是这样的代码:

I was using code like this:

// QML
onSomeSignal: {
  var proto = new MyMessage();  // https://github.com/dcodeIO/protobuf.js
  var bbuf  = proto.encode();   // https://github.com/dcodeIO/bytebuffer.js
  var bytes = bbuf.toBinary();
  messageBridge.send(bytes);
}

// C++
void MessageBridge::send(const QString& data) {
    if(m_tcpSocket->state() == QAbstractSocket::ConnectedState) {
        m_tcpSocket->write(encodeVarint32(data.length()).toLocal8Bit());
        m_tcpSocket->write(data.toLocal8Bit());
    }
}

然而,我发现将 JavaScript 字符串转换为 QString 有时会改变字节(大概是因为编码).

However, I discovered that translating the JavaScript string to a QString was sometimes changing the bytes (presumably because of encodings).

以下代码有效,但效率低下,先将字节缓冲区转换为二进制字符串,然后转换为 JS 数组,再转换为 QVariantList,然后零碎地填充 QByteArray.

The following code works, but it's inefficient, converting the byte buffer to a binary string, then a JS array, converting to a QVariantList and then piecemeal populating a QByteArray.

// QML
onSomeSignal: {
  var bytes = (new MyMessage()).encode().toBinary();
  var bytea = [];
  for (var i=bytes.length;i--;) bytea[i] = bytes.charCodeAt(i);
  messageBridge.send(bytes);
}

// C++
void MessageBridge::send(const QVariantList& data) {
    if(m_tcpSocket->state() == QAbstractSocket::ConnectedState) {
        m_tcpSocket->write(encodeVarint32(data.length()).toLocal8Bit());
        m_tcpSocket->write(data.toLocal8Bit());
        QByteArray bytes(data.length(),'\0');
        for (int i=0; i<data.length(); i++) bytes[i] = data[i].toInt();
        m_tcpSocket->write(bytes);
    }
}

传递 ByteBuffer 的有效方法是什么?或从 QML/JavaScript 到 Qt/C++ 的二进制字符串,以某种方式让我可以写入QTcpSocket?

推荐答案

// QML
onSomeSignal: {
    var bytes = new MyMessage();
    messageBridge.send(bytes.toArrayBuffer());
}

并且数组缓冲区将很好地适合 QByteArray:

and the array buffer will nicely fit into a QByteArray:

// C++
void MessageBridge::send(const QByteBuffer& data) {
    if (m_tcpSocket->state() == QAbstractSocket::ConnectedState) {
        m_tcpSocket->write(encodeVarint32(data.size()).toLocal8Bit());
        m_tcpSocket->write(data);
}

现在请告诉我如何从 C++ 中的 QByteBuffer 到 QML 信号中有用的 protobuf.js 对象:)

Now please tell me how to go the other way from a QByteBuffer in C++ to a useful protobuf.js object in a QML signal :)

这篇关于将二进制数据从 QML 传递到 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆