使用函数指针结构的C封装函数



我必须用C语言编写代码,用户必须灵活地选择任何现有的数据库,写入文件或实现自己的存储机制。我需要将包装器函数重定向到与运行时或编译时选择的存储机制相对应的正确函数。假设我的存储选项是FLATFILE和SQLDB,我的包装器函数是insert(value)。因此,如果我选择FLATFILE作为我的存储,当我调用包装器函数insert(value)时,它应该依次调用向文件写入的函数。如果我选择一个SQLDB, insert(value)应该调用在数据库中插入值的函数。

我知道我可以以某种方式使用函数指针结构来做包装函数,但我不知道如何。

有没有人知道任何文档,链接,例子,等我可以参考,理解和实现这样的东西?任何提示将不胜感激。谢谢!

谢谢!

#define BACKEND_FLATFILE 0
#define BACKEND_SQLDB    1
void insert_flatfile(const t_value *v) {
    ...
}
void insert_sqldb(const t_value *v) {
    ...
}
void (*insert_functions[]) (const t_value *) = {
    insert_flatfile, 
    insert_sqldb,
};
void insert_wrapper(t_value *v, int backend) {
    insert_functions[backend](v);
}

此外,一个后端不同的函数应该被塞进一个结构体中,您应该为这样的结构体创建一个数组,而不是为每个包装器函数创建一个数组。

你可以使用一个简单的版本,如:

struct backend {
   int (*insert)(...);
   int (*remove)(...);
   ...
};
static struct backend db_backend = { db_insert, db_remove, ... };
static struct backend other_backend = { other_insert, other_remove, ... };
const struct backend *get_backend(enum backend_type type)
{
  switch (type)
  {
     case DB_BACKEND:
       return &db_backend;
     case DB_OTHER:
       return &db_other;
     ...
  }
}

以上所有内容都可以隐藏在C文件中,其中get_backend和枚举是公共的。然后你可以这样使用:

struct backend *b = get_backend(DB_BACKEND);
b->insert(...);
b->remove(...);
当然,许多细节都缺失了(例如,许多人喜欢使用typedef)。这是一个基本的设置,如果您不喜欢b->insert(...)语法,或者如果您想设置一次后端,然后在代码中使用insert()remove(),您也可以创建包装器函数。如果你已经有一些直接调用insert()的代码,并且你想将调用引导到正确的后端,这也很有用。

如果您想要更详细的解决方案,请查看http://www.cs.rit.edu/~ats/books/ooc.pdf。你不需要执行它的每一个细节,但它可以给你一些想法。

最新更新