如何为C链表制作C++包装

How to Make a C++ Wrapper for a C Linked List

本文关键字:C++ 包装 链表      更新时间:2023-10-16

我在C中实现了一个链表,其中有许多函数可以帮助简化它的操作
我不想把这个功能移植到C++,所以我试图创建一个简单的包装类,它在内部调用原始函数,并在内部操纵C链表。

对于大多数功能,包装器代码运行良好。然而,有一个问题。C链表结构有指向下一个和上一个C链表结构的指针,我希望能够获得C++等价的类指针。。

我该怎么做?

E.x:有一个C函数,它在索引处获取链中的链表。Original函数的作用如下:

struct _linkedlist *LinkedList_get(struct _linkedlist * list, const unsigned long index)
{ /* Gets the index'th linked list in the chain as a pointer */
    if ((list) == NULL) return NULL;
    if (index >= LinkedList_get_depth(list))
        return NULL;
    for(unsigned int i = 0; i < index; list = list->next, ++i);
    return list;
}

该函数清楚地返回一个指向链表C结构的指针。我想做的是获得一个指向C++链表包装器对象的指针。

这样做的全部目的是,我可以在不更改原始源(C版本)的情况下,围绕纯功能接口(C接口)制作一个面向对象的包装器(C++接口)。

您在评论中提到,您的C链表存储了任意值类型(如void*)。因此,C++包装器在该值类型中存储额外的信息应该是相当琐碎的。这个额外的信息可以是指向相应C++包装器的指针。

你还没有展示你的代码,所以我将以一种通用的方式展示这个想法:

// This is the original C interface
struct C_Node;
void* c_getValue(struct C_Node *node);
struct C_Node* c_insertAfter(struct C_Node *node, void *value);

// This is the C++ wrapper
template <class T>
class Node
{
  C_Node *cNode;
  typedef std::pair<T, Node*> ProxyValueType;
  explicit Node(C_Node *cNode) : cNode(cNode)
  {
    static_cast<ProxyValueType*>(c_getValue(cNode))->second = this;
  }
public:
  T& getValue() const
  { return static_cast<ProxyValueType*>(c_getValue(cNode))->first; }
  Node* insertAfter(T value)
  {
    ProxyValueType *proxy = new ProxyValueType(T, nullptr);
    C_Node *newNode = c_insertAfter(cNode, proxy);
    return new Node(newNode);
  }
};

当然,上面写的是糟糕的C++,因为它使用拥有原始指针等。把它当作这个想法的演示,而不是可粘贴的代码。