2015-06-27 102 views
1

我有一个变量:如何在uint8_t *的末尾添加int?

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. 

此,多个事情happend(什么都无所谓)后,并在年底另一个函数删除页眉附加'myfunction',然后我将这个函数给出的数据转换为struct Data *。我可以访问DTS,PTS的大小,但我有一个SIGSEGV错误的数据..

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

+0

定义一个结构? –

+0

是的,这是一种可能性,但我想用UDP发送我的数据。 –

+0

...那么?发送通常使用指针和大小来完成:'sizeof(struct mystruct)' –

回答

0

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

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 
+0

谢谢,但是当函数读取mydata时,它将只是一个表格? 因为这个函数只接受缓冲区。 –

+0

是的,这个函数看到一些内存的开始加上它的大小,并且不知道内存中包含了什么。 –

+0

哇,非常感谢。我会测试;) –

0

你可能访问附加int值地址与uint8_t的指针。尝试在访问它们时将其转换为int *。

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

+2

编号这有对齐问题 – imallett

+0

@imallett:... **可能**有对齐问题取决于放在两个int之前的'uint8_t'的数量。 – alk