c - 如何在 uint8_t* 的末尾添加一个 int?

标签 c uint8t

我有一个变量:

uint8_t* data

我想为这些数据添加一个标题。刚好是两个数字。 我想要这样的数据:data+my_int+my_second_int

之后,我必须将我的数据提供给一个函数(我无法修改),以及我的数据大小。

像这样:myfunction(data,size);

目前我的代码是这样的:

struct Data {
  uin8_t* data;
  uint32_t PTS;
  uint32_t DTS;
  uint16_t size_data;
};


struct Data* mydata;
mydata->data = data; // data I get before
mydata->size_daza = size; // size I get before
mydata->PTS = GST_BUFFER_PTS(buf);
mydata->DTS = GST_BUFFER_DTS(buf);

myfunction(mydata,sizeof(struct Data)); // My function , this function add also a header to my data (another).I can't access or modify this function.

在此之后,发生了很多事情(无关紧要),最后另一个函数删除了附加有“myfunction”的 header ,然后我将这个函数给出的数据转换为 struct Data*。我可以访问 DTS、PTS 和大小,但我在数据上有一个 SIGSEGV 错误。

我想我必须更改我的结构,但我没有看到其他方式来存储没有指针的缓冲区。

最佳答案

这就是结构的用途。您定义要发送的数据的结构:

struct Data {
  uint8_t data;
  int first_int;
  int second_int;
  // possibly more
};

并将它以指向发送函数开头的指针的形式传递给发送函数 占用的内存(这通常是一个void *)和对应的大小:

struct Data * mydata = // ... wherever that comes from
send_somewhere(mydata, sizeof(struct Data));
// look at the API doc if you are still the owner of the
// memory and if so, free it (if it's no longer needed and
// has been dynamically allocated)

取决于 send_somewhere 的实现方式(例如,如果它不需要 void *), 你可能需要转换它, 例如在您描述的情况下:

send_somewhere((uint8_t*)mydata, sizeof(struct Data));

有一个可能的缺点:结构可能会被优化填充 编译器。填充意味着您将发送比实际需要发送的数据更多的数据。根据编译器的不同,有一些属性 禁止填充:

struct Data {
  // contenst
} __attribute__((__packed__)); // for gcc, and clang

关于c - 如何在 uint8_t* 的末尾添加一个 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31094199/

相关文章:

c - 打印结构体的浮点值

c char 数组到 uint8_t 数组

c++ - 从 uint8_t 到 int 的隐式转换出错了,而显式转换顺利

c++ - 在不移动末尾的情况下删除文件中间的字节?

c++ - 为什么 sizeof(ptrdiff_t) == sizeof(uintptr_t)

索引链表的 C++/STL 结构(哈希表中的索引)

c - MAC地址打印

c - 如何打印 uint8_t 字节数组?

c++ - 将类型分配给 uint8_t 值