1

我有一个变量:

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”的标题,然后我将该函数给出的数据转换为 struct Data*。我可以访问 DTS、PTS、大小,但数据上有一个 SIGSEGV 错误。

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

4

2 回答 2

0

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

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

并将其传递给发送函数,以指向占用内存开始(通常是 a 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实现方式(例如,如果它不采用 a void *),您可能需要强制转换它,例如在您描述的情况下:

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

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

struct Data {
  // contenst
} __attribute__((__packed__)); // for gcc, and clang
于 2015-06-27T22:55:39.927 回答
0

您可能正在使用 uint8_t 指针访问附加的 int 值地址。当您访问它们时,尝试将其转换为 int*。

给我们你的代码,否则我们只是猜测。

于 2015-06-27T23:08:57.060 回答