来自维基文章:
类型和长度大小固定(一般为1-4字节)
所以,我会将nTag 和nLength 更改为一些固定长度的类型。 int 的大小是特定于平台的,这可能会给您带来一些麻烦。为您的协议修复它们的大小并使用int8_t、int16_t 或int32_t 等。对于nLength,您甚至可以使用无符号。
由于值可以是任何类型,我会使用void* 代替pValue,而不是unsigned char*。
你将如何使用这个数据结构?您希望如何访问不同的 TLV?
我的意思是 - 你需要链表吗?或者,对于您的案例/应用程序/目的/等,链表会是最佳选项吗?
我想说的是,您可以删除 pNext 元素并将 TLV 视为(动态增长的)数组的元素。这个真的取决于你的需要。
很可能,当您实现 TLV 时,您需要通过某种连接发送它们,对吗?如果是这样,您需要考虑一些协议。我会做这样的事情 - 一开始就发送 TLV 的总数,我不会使用链表,而是使用动态数组。
您应该小心通过网络发送此类数据结构 - pNext 指针无效,必须在连接的另一端重置它们。
您还需要仔细发送数据,但我想您知道这些事情。我只是想提一下。
编辑我发现您在理解 nested TLV 的含义时遇到了一些麻烦。
嵌套的 TLV 只是一个 TLV 元素,它具有 TLV 类型的值。而这与 TLV 的“容器”——动态数组或链表无关。
这是一个未经测试的示例,只是为了了解这个想法。我会这样做:
struct TLV
{
uint32_t nTag;
uint32_t nLength;
void* pValue;
};
// created dynamic array with 3 TLVs:
TLV* pMyTLVs = malloc( 3 * sizeof( struct TLV ) );
// set the first 2 TLVs, some primitives, for example
// ..
// now, set the third TLV to be nested:
pMyTLVs[ 2 ].nTag = ...; // set some tag, that will indicate nested TLV
pMyTLVs[ 2 ].nLength = ...; // set length of the TLV element
pMyTLVs[ 2 ].pValue = malloc( sizeof( struct TLV ) );
// get pointer to the new, _nested_ TLV:
TLV* pNested = (TLV*)pMyTLVs[ 2 ].pValue;
// now use the pNested TLV as an usual TLV:
pNested->nTag = ...;
pNested->nLength = ...;
pNested->pValue = ...;
// of course, pNested is not absolutely necessary, you may use directly
// pMyTLVs[ 2 ].pValue->...;
// but using pNested, makes the code more clear
注意:再一次,这不是经过测试的代码,但我想你明白了。希望对您有所帮助。