gpt4 book ai didi

c++ - 可变长度结构

转载 作者:太空宇宙 更新时间:2023-11-04 03:58:44 25 4
gpt4 key购买 nike

OMX 提供了一个定义如下的结构体

/* 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. */

我有一个常量字符数组要设置。

char* filename = "/test.bmp";

据我所知,我需要以某种方式将 memcopy 文件名设置为 struct.contentURI,然后相应地更新 struct.size。我该怎么做?

最好的问候

最佳答案

首先你需要分配足够的内存来容纳固定大小的部分和文件名:

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);

加 1 以包含终止符,减 1 是因为该结构已包含一个字节的数组。

在 C++ 中,您需要强制转换,并且您应该使用智能指针或 vector 来确保异常安全:

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

然后您可以填写字段:

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

完成后不要忘记free(param)

关于c++ - 可变长度结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13992914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com