0

如何使用 msgpack_pack_raw 和 msgpack_pack_raw_body 发送一个 unsigned char 数组,更重要的是,如何检索(解包)它?我所做的如下:

msgpack_sbuffer* buffer = msgpack_sbuffer_new();
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
msgpack_sbuffer_clear(buffer);
msgpack_pack_array(pk, 10);

unsigned char a[10] = "0123456789";
msgpack_pack_raw(pk, 10);
msgpack_pack_raw_body(pk,a,10);

在接收器部分我有:

msgpack_unpacked msg;
msgpack_unpacked_init(&msg);
msgpack_unpack_next(&msg, buffer->data, buffer->size, NULL);
msgpack_object obj = msg.data;
msgpack_object* p = obj.via.array.ptr;
int length = (*p).via.raw.size;
IDPRINT(length);
unsigned char* b = (unsigned char*) malloc(length);
memcpy(b,(*p).via.raw.ptr,length);

但是在执行“int length = (*p).via.raw.size;”时会引发段错误。

知道为什么吗?

4

1 回答 1

0

知道为什么吗?

这是因为msgpack_pack_array(pk, 10);这里不需要,因为您将数据打包为给定大小的原始缓冲区。换句话说msgpack_pack_rawmsgpack_pack_raw_body就足够了。

在解包时,您必须按如下方式访问其字段:

  1. 长度:obj.via.raw.size
  2. 数据:obj.via.raw.ptr

见:msgpack_object_rawobject.h

以下是如何进行的回顾:

#include <stdio.h>
#include <assert.h>
#include <msgpack.h>

int main(void) {
  unsigned char a[10] = "0123456789";

  char *buf = NULL;
  int size;

  /* -- PACK -- */
  msgpack_sbuffer sbuf;
  msgpack_sbuffer_init(&sbuf);
  msgpack_packer pck;
  msgpack_packer_init(&pck, &sbuf, msgpack_sbuffer_write);

  msgpack_pack_raw(&pck, 10);
  msgpack_pack_raw_body(&pck, a, 10);

  size = sbuf.size;
  buf = malloc(sbuf.size);
  memcpy(buf, sbuf.data, sbuf.size);
  msgpack_sbuffer_destroy(&sbuf);

  /* -- UNPACK -- */
  unsigned char *b = NULL;
  int bsize = -1;

  msgpack_unpacked msg;
  msgpack_unpacked_init(&msg);
  if (msgpack_unpack_next(&msg, buf, size, NULL)) {
    msgpack_object root = msg.data;
    if (root.type == MSGPACK_OBJECT_RAW) {
      bsize = root.via.raw.size;
      b = malloc(bsize);
      memcpy(b, root.via.raw.ptr, bsize);
    }
  }

  /* -- CHECK -- */
  assert(bsize == 10);
  assert(b != NULL);
  for (int i = 0; i < bsize; i++)
    assert(b[i] == a[i]);

  printf("ok\n");

  free(buf);
  free(b);

  return 0;
}
于 2013-10-14T07:41:04.420 回答