Variable length structures

冷暖自知 提交于 2019-12-11 08:14:49

问题


OMX provides a struct with following definition

/* Parameter specifying the content URI to use. */
typedef struct OMX_PARAM_CONTENTURITYPE
{
OMX_U32 nSize;
/**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
OMX_U8 contentURI[1];     /**< The URI name*/
}OMX_PARAM_CONTENTURITYPE;
OMX_IndexParamContentURI,
/**< The URI that identifies the target content. Data type is OMX_PARAM_CONTENTURITYPE. */

I have got a constant char array to set.

char* filename = "/test.bmp";

As far as I understood I need somehow to set memcopy filename to struct.contentURI and then to update the struct.size accordingly. How can I do it?

Best regards


回答1:


First you need to allocate enough memory to contain the fixed-size parts and the filename:

size_t uri_size = strlen(filename) + 1;
size_t param_size = sizeof(OMX_PARAM_CONTENTURITYPE) + uri_size - 1;
OMX_PARAM_CONTENTURITYPE * param = malloc(param_size);

adding 1 to include the termination character, and subtracting 1 because the structure already contains an array of one byte.

In C++, you'll need a cast, and you should use a smart pointer or a vector for exception safety:

std::vector<char> memory(param_size);
OMX_PARAM_CONTENTURITYPE * param = 
    reinterpret_cast<OMX_PARAM_CONTENTURITYPE *>(&memory[0]);

Then you can fill in the fields:

param->nSize = param_size;
param->nVersion = whatever;
memcpy(param->contentURI, filename, uri_size);

and don't forget to free(param) once you've finished with it.



来源:https://stackoverflow.com/questions/13992914/variable-length-structures

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!