創建回調和結構爲重複場的protobuf的消息中nanopb我有限定的原消息爲:在C
message SimpleMessage {
repeated int32 number = 1;}
現在,編譯後,場是pb_callback_t
,我想編寫功能。 (沒有.options文件)
現在,在哪裏以及該函數應包含哪些內容?數據本身存儲在哪裏以及如何訪問數據/向其分配新數據?
*編輯*
根據@Groo的答案,這是我嘗試的代碼:
typedef struct {
int numbers_decoded;
} DecodingState;
bool read_single_number(pb_istream_t *istream, const pb_field_t *field, void **arg)
{
// get the pointer to the custom state
DecodingState *state = (DecodingState*)(*arg);
int32_t value;
if (!pb_decode_varint32(istream, &value))
{
const char * error = PB_GET_ERROR(istream);
printf("Protobuf error: %s", error);
return false;
}
printf("Decoded successfully: %d", value);
state->numbers_decoded++;
return true;
}
int main(void) {
int32_t arr[3] = {10, 22, 342};
uint8_t buffer[128];
size_t message_length;
bool status;
SimpleMessage simple = SimpleMessage_init_zero;
printf("\nbefore : arr[0] = %d\n",arr[0]);
// set the argument and the callback fn
simple.number.arg = &arr;
simple.number.funcs.decode = read_single_number;
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
status = pb_encode(&ostream, SimpleMessage_fields, &simple);
message_length = ostream.bytes_written;
SimpleMessage simple1 = SimpleMessage_init_zero;
simple = simple1;
arr[0] = 0;
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// this function will call read_single_number several times
status = pb_decode(&istream, SimpleMessage_fields, &simple);
printf("\nafter : arr[0] = %d\n",arr[0]);
return EXIT_SUCCESS;
}
並且輸出是:
之前:ARR [ 0] = 10
解碼成功:17
後:常用3 [0] = 0
我該怎麼辦錯了嗎?
它不起作用。將我的代碼添加到原始問題中。 –
@ItayPupko:你使用了錯誤的(解碼)回調進行編碼,應該有兩個單獨的回調(一個用於寫入,一個用於讀取)。我已經用編碼和解碼代碼更新了我的答案。 – Groo