如何为C链表制作C++包装
How to Make a C++ Wrapper for a C Linked List
我在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++,因为它使用拥有原始指针等。把它当作这个想法的演示,而不是可粘贴的代码。
相关文章:
- 如何在c++17中制作一个模板包装器/装饰器
- std::vector的包装器,使数组的结构看起来像结构的数组
- 如何在c++迭代器类型中包装std::chrono
- 是否可以用"iostream"包装现有的TCP/OOpenSSL会话
- 用pybind11包装C++抽象类时出错
- 为左值和右值的包装器实现C++范围
- C结构,其指针将被包装在unique_ptr中
- 如何包装第三方DLL在R中使用
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 将 N-arg 函数包装到另一个函数中
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 包装一个对象并假装它是一个 int
- 使用 Python Extension API 包装复杂C++类
- 外壳包装器句柄/执行交互式命令管道C++ UNIX
- 包装C++类时不完整的类型 GLFWwindow
- 将函数包装器转换为 std::function
- C++函数包装器来捕获某些信号
- 创建包装升压适配器的自定义范围类
- 如何包装(撰写)增强 hana 地图并访问括号运算符(运算符 [])?
- 使用运算符*重载包装矩阵乘法