Copy a std::vector to a repeated field from protobuf with memcpy

后端 未结 3 1618
再見小時候
再見小時候 2020-12-15 06:49

At first I have this simple protobuf file

message messagetest
{
    ...
    repeated float samples = 6;
    ....
}

Which creates a headerfi

相关标签:
3条回答
  • 2020-12-15 07:29

    Since this isn't here yet and I like one-liners:

    *fMessage.mutable_samples() = {fData.begin(), fData.end()};
    
    0 讨论(0)
  • 2020-12-15 07:35

    I found the shortest way to copy vector into repeated field as this:

    google::protobuf::RepeatedField<float> data(fData.begin(), fData.end());
    fMessage.mutable_samples()->Swap(&data);
    

    It is probably also faster than yours since it avoids initial iteration and setting values to 0.

    0 讨论(0)
  • 2020-12-15 07:46
    fMessage.mutable_samples()
    

    return an array of pointer of samples : [*sample1, *sample2, sample3, ...].

    &fData[0]
    

    is the address of first element of fData.

    memcpy(fMessage.mutable_samples()->mutable_data(),
         &fData[0],
         sizeof(float)*fData.size());
    

    So I do not think the code above can successfully fill data from fData to fMessage. It's totally wrong!

    0 讨论(0)
提交回复
热议问题