简体   繁体   English

在GRPC中使用字节数组(cpp)

[英]Using byte array (cpp) in GRPC

I am having a lot of trouble with GRPC when using byte array. 使用字节数组时,我在使用GRPC时遇到很多麻烦。 This is by .proto 这是.proto

message myType {
    int32 format = 1;
    bytes data = 2;
}

I am using CPP for Server implementation and Java for Client. 我将CPP用于服务器实现,将Java用于客户端。 Using ByteString in Java is a breeze but cannot deserialize in CPP (byte[] being changed from what was being sent from Java). 在Java中使用ByteString轻而易举,但不能在CPP中反序列化(从Java发送的字节[]更改为字节[])。

buffer is a byte[] byte buffer[<large_size>] And I'm converting the byte array (it's an image) into a smaller byte array, and it's crashing when trying to convert the byte[] received from grpc. 缓冲区是一个byte [] byte buffer[<large_size>]并且我正在将字节数组(它是一个图像)转换成一个较小的字节数组,当尝试转换从grpc接收到的byte []时,它崩溃了。 The conversion function in CPP is good as I used it with the same image before using GRPC CPP中的转换功能很好,因为我在使用GRPC之前将其用于相同的图像

This is the deserialization code for CPP. 这是CPP的反序列化代码。 Here "req" is a myType object, and buffer is a byte[] 这里“ req”是一个myType对象,而缓冲区是一个字节[]

myFormat = req->format();
dataLen = req->data().length();
memcpy(buffer, req->data().c_str(), dataLen);

From what I understand, req->data() is in cpp std::string format 据我了解,req-> data()是cpp std :: string格式

On the client side, you should pass both the parameter and its length. 在客户端,您应该同时传递参数及其长度。 parameter.set_framemat(mat, 12);

Do check if the length of the array at the server side is not zero. 请检查服务器端数组的长度是否不为零。 Note that bytes is char array and grpc is de marshalling it as string. 请注意,字节是char数组,而grpc将其作为字符串解组。 So if say the array is filled with null characters the data length comes as zero. 因此,如果说用空字符填充数组,则数据长度为零。

I was trying a similar use case 我正在尝试类似的用例

Proto file 原始文件

message Parameters {
      bytes framemat = 16; 
};

Client Snippet 客户片段

const char mat[12] = {0}
parameter.set_framemat(mat);
stream->Write(parameter);

Server Snippet 服务器片段

std::thread reader([&]() {

    ::nokia::nas::Parameters request;
    while (stream->Read(&request))
    {
      //get the params
       grpc::string mat = request.framemat();
      logger->info(" Length of Bytes= {} , mat.length()}

Output was zero! 输出为零! So I changed the client input to check with some char strings and sure enough the data length was coming as 4 at the server side; 因此,我更改了客户端输入以检查一些字符字符串,并确保足够的数据长度在服务器端为4; because this time it was a valid string and string length matched. 因为这次是有效的字符串,并且字符串长度匹配。

const char mat[12] = "sdsd";

Better way is to specify in the proto the data as well as the data length 更好的方法是在原型中指定数据以及数据长度

message StreamBytes { 
  bytes data_bytes =1;
  int32 data_length = 2;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM